How to use useEffect in React?
Introduction
Earlier , we talk about what are useEffect hooks and why we should use them in our application, to handle side effects like handling http requests , setting timers and intervals and many more . Why useEffect has place so much importance in react? you must know the answer to this question , only then using useEffect will be fun to use in react application and writing code with the understanding is much more important than just cramping the syntax of the concept.
There are three case scenarios in which the useEffect hook can be used and provides the much code flexibility
1. UseEffect runs only once
This is the case scenario in which we want to run the useEffect hook only when the page loads initially and then it never changes. The side effect function in the useEffect hook will only run in initial render and will not re-render useEffect hook , if any state changes or component re-evaluated. Let's look at the example of the useEffect hook below,
So, you see when you run the useEffect only once , you will specify nothing in the dependency list and have to placed the empty array in the second parameter of the hook , first parameter is the side effect function which will only run initially whenever the page loads.
In this example , the set timeout function console log 1 after one second only once when the page loads. This is very simple example of useEffect hook which will runs initially .
2. UseEffect hook runs on every render
UseEffect hook runs on every render when you don't specify the second parameter which is the dependency list and will only contain the side effect function which in result be execute whenever some state in you code updates and re-executed the side effect function every time. Let's look at the example of the useEffect hook runs on every render below,
This is the pretty easy example of useEffect hook , where in the component with any state update useEffect hook will console log 1 after a second and log the value 1 when the component re-executed.
3. UseEffect hook runs conditionally
If you want to run the useEffect hook only when some of the your state changes in your component , you have to specify the dependency list in the second parameter , the way we did when hook renders only once but not as empty array , it will contain the current value of the state or the prop , so it can compare the values , and on the basis of the comparison hook function executes. Let's look at the example below,
In this example , whenever the onClick event triggers , it updates the count values which re-renders the component and also runs the side effect because the count value specify in the dependency list . This is how you use useEffect hook conditionally and can specify the state or prop value in the dependency list according to your use case in the project.
Thank you for reading the blog post!
Comments
Post a Comment