Introduction to React
The effect hook lets us perform side effects inside the component. For example, fetching data from an API, running a timer, updating another component/element, etc.
We will try to understand the importance and usefulness of effect hook by looking at an example.
Let's try making a simple component that contains a
<h1> element. The element displays the text from the
message state variable. We will use a timer inside the component function to update the message text after 4 seconds:
Note that we also included a
console.log statement inside the timer function for debugging.
If we use the above code, the output should be something like this:
It does change the text after four seconds, however, if you look at the console, the
log indicates that the timer function has been called multiple times!
This is because every time the component is re-rendered, the component's function is re-executed, and since the component's function contains the timer code as well, the timer runs again. This is not what we want.
This can be especially problematic in cases, for example, when we make API calls or perform other tasks that are not supposed to be repeated.
useEffect function lets us perform tasks like these without worrying about how often the component will be re-rendered.
The function passed into
useEffect is executed independently of how often the component is re-rendered.
The syntax for the
useEffect is the following:
<function> is usually an inline function that contains the code for performing the side effect we want, and
<dependency> is supposed to be an array of terms (or values) that are supposed to be tracked for any changes.
The inline function will be executed if there are changes in any of the dependencies.
In the above code, on every 10th value, the state variable
tens is incremented.
useEffect is set to execute only when there are changes in
We can see the debug log to confirm this:
If you look at the console,
"useEffect called" is printed after every 10th value.
However, if we pass an empty array as a dependency in the
useEffect function, the function will execute only once after the first render.
This can be used to fix our first example:
The console will show only one log statement since the function is executed only once:
You can use
useEffectmultiple times in a single component based on the needs.