Languages

React - how to call function with useEffect only once

0 points
Asked by:
Selina-Miranda
337

React useEffect hook runs the passed function on every component change or when anything in the array of dependencies changes.

What if I want to call initializeData function like in the class components componentDidMount method and not call it again on change?

my component:

const App = () => {
  useEffect(() => {
      initializeData(); 
  });
  return (
    <div>
      ...
    </div>
  );
}
1 answer
0 points
Answered by:
Selina-Miranda
337

I've read about it and prepared the solution:

You need to create useEffect hook with an empty array of dependencies. That tells React to execute the effect only once (at component mount).

Solution:

const App = () => {
  useEffect(() => {
      initializeData(); 
  }, []);
  return (
    <div>
      ...
    </div>
  );
}

Note:

Check our React - useEffect hook atricle for more runnable examples.

0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join