useEffect Example
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
You clicked {count} times
);
}
When you add useEffect hook in your React code, it knows that you want to execute some code after React is done rendering.
React do that by remembering a function we pass. In the example above, React remembers the function we passed in useEffect and will call it after render.
Let’s understand useEffect hook in the example above.
First we have declared a state variable named count and we’re telling React to use an effect. Then we are passing an arrow function to the useEffect Hook which is called an effect. Inside that function, we’re changing the document title. When React is done rendering, it runs the effect.
By default, useEffect runs after the first render as well as it runs after every time the DOM gets updated. Those are default settings but React also provides a way to customize that.
How does useEffect access the props?
JavaScript function scope and closures plays an important role here. Hooks uses JavaScript closures and use the props and variables that are in function scope.
That is the reason we keep useEffect inside the component so that it can access the props and variables inside the function.
React guarantees the DOM has been updated by the time it runs the effects.
Additional notes
- We pass a different function to useEffect each time. That means each time we render, we run a different effect replacing the previous effect. It’s like each render has its own effect too.
- React Lifecycle Methods like componentDidMount or componentDidUpdate block the browser when they are waiting for something. useEffect doesn’t do that as they happen asynchronously.
functions hook useEffect useState