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:
xxxxxxxxxx
1
const App = () => {
2
useEffect(() => {
3
initializeData();
4
});
5
return (
6
<div>
7
...
8
</div>
9
);
10
}
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:
xxxxxxxxxx
1
const App = () => {
2
useEffect(() => {
3
initializeData();
4
}, []);
5
return (
6
<div>
7
...
8
</div>
9
);
10
}
Note:
Check our React - useEffect hook atricle for more runnable examples.
0 commentsShow commentsAdd comment