DEV Community

Cover image for Run useEffect Only Once :React
Harish Sankaramanchi
Harish Sankaramanchi

Posted on

Run useEffect Only Once :React

Alt Text
If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.
If you pass an empty array ([]), the props and state inside the effect will always have their initial values. While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often. Also, don’t forget that React defers running useEffect until after the browser has painted, so doing extra work is less of a problem.

Top comments (1)

Collapse
 
lexlohr profile image
Alex Lohr

Also if you only want to run it on unmount, you can use

useEffect(() => onUnmountHandler, [])
Enter fullscreen mode Exit fullscreen mode

onUnmountHandler will then be called after the component unmounts.