DEV Community

Cover image for How to run useEffect() only once in React.js - (React Hooks)
Mamun Abdullah
Mamun Abdullah

Posted on

How to run useEffect() only once in React.js - (React Hooks)

import {useEffect} from "react";
Enter fullscreen mode Exit fullscreen mode

Just add an empty array
after the callback function
separated by a comma

useEffect(callback, []);

useEffect(()=>{}, []);
Enter fullscreen mode Exit fullscreen mode

Why do you need to run useEffect() only once?

When you setState inside useEffect() from a data source, it will be continuously updating with the source value, and outside the useEffect() if you have an onChange event handler to setState to another value- that won't work. To solve this, you need to call useEffect() only once.

Oldest comments (0)