Search code examples
javascriptreactjsreact-hooksfrontend

Why useEffect runs ervery time when component <PostList/> loaded from Home component


I have working on a Social media Application and getting stuck with this.

Inside src > component > PostListI have useduseEffect``` with empty dependency array but whenever I went createPost inside SideBar and come Back useEffect again render that causes me not able to add any extra post .

https://github.com/santukumar01/learningreact/tree/main/Social Media App - version- 2

How to resolve this and why every useEffect is runnung .


Solution

  • Your useEffect is re-running because the components are remounting every time selectedTab in your Sidebar.jsx changes:

    {selectedTab === "home" ? <PostList /> : <CreatePost />}
    

    To fix this I recommend moving your data fetch into a more stable place like context or an external state management solution like zustand, then passing the data as props to PostList.