Definition
The useEffect hook is used to handle the side effect of React functional components outside of returning JSX. For instance, fetch data from an API when a component loads. Another example consists of starting or stopping a timer. Also, the useEffect allows to make manual changes to the DOM.
Any code defined inside the useEffect hook will run after React components finished the DOM updates. By default, useEffect runs both after the first render as well as whenever the component's state updates.
useEffect Dependencies Array
The default behavior of useEffect does not always agree with the purpose of our code. To adjust this behavior, we can run useEffect hook functions conditionally using dependencies array.
- Empty array of dependencies[]:
for Example, we only need to run a fetch call to an API once after the JSX has completely loaded. Adding an empty dependencies array as a second argument to the useEffect function will stop the fetch call to API from happening with every re-render of the components. Therefore, the fetch call will only occur when the component renders for the first time.
- Dependencies array with one or more elements [element1, element2,..]:
Using the example of an incrementing counter running as a side effect. We can add the counter variable to the dependencies array. Therefore, the useEffect will run every time our counter state changes.
Conclusion
- Using useEffect with no dependencies array means that the side effect will run every time the component renders and whenever state or props change.
- Using useEffect with an empty dependencies array means the side effect will only run the first time the component renders. No state is involved in this case.
- Using useEffect with dependencies with elements in it means that the side effect will run every time those elements/variables change. The side effect will be triggered by the state changes of the elements inside the dependencies array.
Top comments (0)