Search code examples
reduxreact-reduxdestructuringdispatch

How to destructure an Array from an Object in Redux React?


I am using redux and I want to destructure teamMembers - Array from an Object name - teamData which I am getting from REDUX. This is what I have done below. I just want to confirm whether is this the right way to do.

  const teamData = useSelector((state) => state.team.teamData);
  const { description, heading } = teamData;
  const teamMembers = useSelector((state) => state.team.teamData.teamMembers);

Solution

  • If possible, you should not do

      const teamData = useSelector((state) => state.team.teamData);
      const { description, heading } = teamData;
    

    Your code here is interested in description and heading, but your useSelector selects the whole teamData. Now, if there is a third property on teamData, let's say winStreak and that winStreak changes, your component will rerender. Because that change to winData.teamStreak caused winData to change. And your useSelector is watching winData for changes.

    If you instead do

    const description = useSelector((state) => state.team.teamData.description);
    const heading = useSelector((state) => state.team.teamData.heading );
    

    your component will only rerender, when description or heading change. Because your useSelector now watches those two properties for changes. It does not care if teamData changes, it only cares if teamData.descriptionorteamData.heading` change.

    So, in your case you should do

    const description = useSelector((state) => state.team.teamData.description);
    const heading = useSelector((state) => state.team.teamData.heading );
    const teamMembers = useSelector((state) => state.team.teamData.teamMembers );
    

    and not use any destructuring here. If you have to destructure the result of a useSelector call, that likely means that your useSelector call is also observing data you are not interested in in the first place.