skip to Main Content

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

Inside src > component > PostList I have used useEffect 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/learning-react/tree/main/Social%20Media%20App%20-%20version-%202

How to resolve this and why every useEffect is runnung .

2

Answers


  1. 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.

    Login or Signup to reply.
  2. One way to prevent unnecessary re-renders of the PostList component is
    to use a key prop on it and change the key whenever you want it to
    remount. Since you’re using tabs to switch between different views
    ("home" and "Create Post"), you can use the selected tab as a key for
    the PostList component. This way, whenever the selected tab changes,
    React will treat it as a different component and remount it, causing
    the use effect to run only when necessary.

    Most of the time, I use a key in the map, and I can use it in the component, the key works
    similarly
    to react. memo. when you change the tab and increase the key value, the
    the component renders after the component check key is changed.

    function App() {
      const [selectedTab, setSelectedTab] = useState("home");
      const [postListKey, setPostListKey] = useState(0);
    
      useEffect(() => {
        setPostListKey(prevKey => prevKey + 1);
      }, [selectedTab]);
    
      return (
        <PostContexProvider>
          <div className="app-container">
            <SideBar setSelectedTab={setSelectedTab} selectedTab={selectedTab} />
            <div className="content">
              <Header />
              {selectedTab === "home"? <PostList key={postListKey} /> : <CreatePost />}
              <Footer />
            </div>
          </div>
        </PostContexProvider>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search