How to run useEffect only once in React
In the case of React function components, hooks are used to manage special events. The useEffect
hook will run every time the component is rendered.
useEffect(() => {
// Runs on every render
});
However, in a lot of cases, this is not what you want. For example, if you implement some component initialization, then you want to execute the code only at the first rendering.
Limit useEffect to run only once
Fortunately, the react developers thought of that. You can conditionally fire an effect. To achieve this, you only need to specify a second parameter for the useEffect
method.
This second parameter is an array where you can define props and states your effect should depend on. If the array is empty then react only execute your code at the time of first rendering.
useEffect(() => {
// Initialization code comes here
}, []);