I brought the code below for easy understanding. Note the location of the a function.
There are declarative differences depending on where the a function is in React.
Both are code that works correctly.
Are there any benefits of defining them within React components?
JavaScript
x
20
20
1
function a(init, sub_name, value) {
2
let t2 = cloneDeep(init);
3
t2[sub_name] = value;
4
return t2;
5
}
6
7
export default function test(props) {
8
const [obj, setobj] = useState({
9
first: { id: 123, v: 456 },
10
});
11
12
return (
13
<div>
14
<Test
15
onUpdateData={(v) => setobj((p) => a(p, "first", v))}
16
/>
17
</div>
18
);
19
}
20
JavaScript
1
20
20
1
export default function test(props) {
2
const [obj, setobj] = useState({
3
first: { id: 123, v: 456 },
4
});
5
6
function a(init, sub_name, value) {
7
let t2 = cloneDeep(init);
8
t2[sub_name] = value;
9
return t2;
10
}
11
12
return (
13
<div>
14
<Test
15
onUpdateData={(v) => setobj((p) => a(p, "first", v))}
16
/>
17
</div>
18
);
19
}
20
- This is a shortened code that makes it easy to understand the intent of the question.
Advertisement
Answer
In the first snippet you posted, the a
function is essentially a private function in that file. It is used by your export but it is not accessible to other scopes.
In the second snippet, you have used a closure to encapsulate the a
function, which is part of the exported function.