最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React useEffect (with []) is called every time I change page (React Router) - Stack Overflow

programmeradmin0浏览0评论

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 (ponents 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 ponent 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 ponent and it's not a case.

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 (ponents 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 ponent 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 ponent and it's not a case.

Share Improve this question edited Oct 25, 2019 at 11:00 Sohail Ashraf 10.6k3 gold badges30 silver badges43 bronze badges asked Oct 25, 2019 at 9:51 kamparkampar 531 silver badge3 bronze badges 1
  • 4 @Rajesh no, that's wrong. An empty array means it will only run when the ponent mounts, and that's it. It will be called again if the ponent is unmounted, then mounted again. – Kobe Commented Oct 25, 2019 at 9:58
Add a ment  | 

1 Answer 1

Reset to default 8

An empty deps array means that the useEffect will only be called each time the ponent is mounted. The useEffect is being called every time you change the page because the page ponent 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 ponent, and call your fetch there instead. However, I'm not sure that can be done with a class ponent, so you might have to use a function ponent instead.

发布评论

评论列表(0)

  1. 暂无评论