DEV Community

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

Posted on

4 1

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.

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay