Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  156] [ 4]  / answers: 1 / hits: 6605  / 5 Years ago, fri, october 25, 2019, 12:00:00

I prepared small demo for the problem:



Demo



So I am using react-router-dom to create Single Page Application and I created standard navigation between two pages (components Page1 and Page2).



Problem is that every time I switch between pages then useEffect hook (with empty array as second argument) is called (on demo you can see it in console).



I would want to fetchData for each component only once and reuse that data after, no matter if user will switch between pages. Is there possibility to do it without checking some conditions inside useEffect function? It's a little confusing to me, because useEffect [] should run only once for component and it's not a case.


More From » reactjs

 Answers
10

An empty deps array means that the useEffect will only be called each time the component is mounted. The useEffect is being called every time you change the page because the page component is being unmounted each time, then remounted when you visit it again. For example, try clicking the page 1 link twice. It will only log the message once, because the page is not being unmounted and remounted.



You could try to fix this problem by using the useEffect a level higher than the page, which would be your app component, and call your fetch there instead. However, I'm not sure that can be done with a class component, so you might have to use a function component instead.


[#5817] Wednesday, October 23, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
daja questions
Tue, Dec 21, 21, 00:00, 2 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
Tue, Jul 23, 19, 00:00, 5 Years ago
Sat, Apr 27, 19, 00:00, 5 Years ago
;