5

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.

1
  • 4
    @Rajesh no, that's wrong. An empty array means it will only run when the component mounts, and that's it. It will be called again if the component is unmounted, then mounted again. Commented Oct 25, 2019 at 9:58

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

another interesting way to see this behaviour would be to swap out the Page2 from being passed to the component prop on the routes so they both render the Page1 like component={Page1}, it's intrinsic to the Route components that they unmount when the path changes in that setup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.