What is side-effect in ReactJS and how to handle it?
What is side Effects
ReactJS is a UI library. Its job is to render the UI and update it on the user's interaction or events. Eg: if a user has clicked on a button then update the UI accordingly. However, many events don't require any user interaction or event. E.g.: API data on a load of applications, a user has logged in and we want to keep the user's information and update the themes, or other information. Such requirements that don't need any user events or interaction are known as "side effects" in ReactJS.
Why do we need side effects
There are a lot more operations in ReactJS that won't require user's events/interactions but they are crucial to do the application work.
What is the use effect hook
useEffect() is a hook by ReactJS and it allows us to handle such side effects in the react component. It gives us the correct way to handle the side effects in ReactJS code.
syntax of use effect
useEffect(() => {}, []);
use effect()
has 2 parts:
- method: Here we will write our side effect code.
Dependencies: The Dependencies array is a place where we declare dependencies and which will decide when use effect() should execute.
use effect() & dependency array
useEffect() also works as the lifecycle hook in ReactJS. This would depend on the dependency array.
- Omit dependency array
useEffect(() => {
console.log('I am running');
})
This will run every time the component re-renders and 1st time too. This is componentDidMount
, and componentDidUpdate
lifecycle hooks.
We should keep those side effects here which you want every time the component is re-rendering.
- Blank dependency array
useEffect(() => {
console.log('I am running');
},[])
This will run only once at the initial amount of the component and after that it won't run. You can have those side effects that you only want the first time of mount your component. E.g.: API request.
- Value in dependency Array
useEffect(() => {
console.log('I am running');
},[ count ])
Here we have added a state in the dependency array. This will make the effect to run once at the load time, and then whenever the state count changes. This will act as the componentDidUpdate
and componentDidMount.
- Clean up
If we need to do any cleanup of side-effect before the unmounting, and component re-render before the component re-render due to a change in the state we can use the useEffect to do the same.
Please remember this is optional
useEffect(() => {
console.log('I am running');
return () => {
// your clean up code
}
},[ count ])
Happy