I have some question while working with React.js. Say we have those useEffects that have the same dependencies inside some a.jsx:
// a.jsx
const Main = () => {
useEffect(() => {
console.log(1);
}, []);
useEffect(() => {
console.log(2);
}, []);
return <p>asdf</p>
}
In a b.jsx, I've gathered functions to have one useEffect, like below:
//b.jsx
const Main = () => {
useEffect(() => {
console.log(1);
console.log(2);
}, []);
return <p>asdf</p>
}
What is the different? Which one is the best practice?
Having many useEffects is not a problem, but for maintainability, if it is possible, having one is a best choice. However, in some cases you can't, for example if you have different logics to execute or different dependencies like so :
const Main = () => {
// this one runs one time when the component mounts the first time
useEffect(() => {
console.log(1);
}, []);
// this one runs every time someVarible changes and when the component mounts the first time
useEffect(() => {
console.log(2);
}, [someVariable]);
return <p>asdf</p>
}
The best practice(s) are the ones that:
That last one I think is applicable here. An useEffect with an empty dependency array is roughly equivalent to the componentDidMount lifecycle. A component can only be mounted once per mounting, so you can reduce (not repeat) code by placing all mounting logic into a single mounting useEffect hook.
// b
useEffect(() => {
console.log(1);
console.log(2);
}, []);
If some logic has the same dependencies later during rerenders, then logically it still makes sense to place them into a single effect hook.
// b
useEffect(() => {
console.log(1);
console.log(2);
}, [depA, depB]);
Even if they have the same dependencies but you want to conditionally call some functions internally, still it makes sense to place them into a single effect hook.
// b
useEffect(() => {
console.log(1);
if (depB) {
console.log(2);
}
}, [depA, depB]);
It's when the dependencies are different that you'll want to use separate effects.
// a
useEffect(() => {
console.log(1);
}, [depA]);
// b.jsx
useEffect(() => {
if (depC) {
console.log(1);
}
console.log(2);
}, [depB, depC]);