Use one or many useEffect in component
useEffect hook is used to execute some logic after rendering the component. React calls the function passed to the “useEffect” on the initial render or re-render of a component.
There might be a situation where you need to trigger an API call and also change a value of state only on the initial rendering of the component. In this case, it is a good idea to use a single useEffect to call the API and set the state value. And to render the effect only once you need to pass an empty array in the second parameter of the useEffect.
let [singleRender, setSingleCount] = useState(0); useEffect(() => { axios.get(`https://jsonplaceholder.typicode.com/users`) .then(res => { console.dir(res.data); }) alert("Component Single Render Called"); }, []);
Again, in some cases when you need to perform different actions to change different state values. In such a case, it is good to separate out into different useEffect. And if you want to see the side effect whenever the state value is changed.
let [multipleRender, setMultipleRender] = useState(0); let [multipleRenderTwo, setMultipleRenderTwo] = useState(0); useEffect(() => { alert("Component Multiple Render Updated..."); }, [multipleRender]); useEffect(() => { alert("Component Multiple Render Two Updated..."); }, [multipleRenderTwo]);
Now, if you want to see the side effect, your final component will look like this,
let [multipleRender, setMultipleRender] = useState(0); let [multipleRenderTwo, setMultipleRenderTwo] = useState(0); let [singleRender, setSingleCount] = useState(0); useEffect(() => { alert("Component Multiple Render Updated..."); }, [multipleRender]); useEffect(() => { alert("Component Multiple Render Two Updated..."); }, [multipleRenderTwo]); useEffect(() => { axios.get(`https://jsonplaceholder.typicode.com/users`) .then(res => { console.dir(res.data); }) alert("Component Single Render Called"); }, []); return ( <div className="App"> <b>Multiple Render Count: {multipleRender}</b> <button onClick={() => setMultipleRender(multipleRender + 1)}>Add Multiple Render</button><br/> <b>Multiple Render Two Count: {multipleRenderTwo}</b> <button onClick={() => setMultipleRenderTwo(multipleRenderTwo + 1)}>Add Multiple Render Two</button><br/> <b>Single Render Count: {singleRender}</b> <button onClick={() => setSingleCount(singleRender + 1)}>Update Single Render</button> </div> );