'several useEffect with same deps
I have some question while developing ReactJS
// a.jsx
const Main = () => {
useEffect(() => {
console.log(1);
}, []);
useEffect(() => {
console.log(2);
}, []);
return <p>asdf</p>
}
//b.jsx
const Main = () => {
useEffect(() => {
console.log(1);
console.log(2);
}, []);
return <p>asdf</p>
}
Such like a.jsx, there are some several useEffect that have same deps.
b.jsx, I've gathered functions by one useEffect
What is different? which one is the best practice?
Thank you
Solution 1:[1]
Having many useEffect is not a problem, but for maintainability, if it is possible, having one is a best choice. However, in some case you can't, for example if you have different dependencies like so :
const Main = () => {
// this one runs one time when the component mount the first time
useEffect(() => {
console.log(1);
}, []);
// this one runs every time someVarible changes and when the component mount the first time
useEffect(() => {
console.log(2);
}, [someVariable]);
return <p>asdf</p>
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
