EN
React - how to call function with useEffect only once
1
answers
0
points
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
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