0

I would have guessed that this question is a dupe, but I searched and I can't find it... Full source for this q is here: https://github.com/micahg/arraytest.

Using react, I'm mapping an array of objects (stored with useState) to a component for display. I'd like react to only render objects in the array with changed properties - but anything I've tried either renders every member or none. The (simplified) component:

const ContainerComponent = () => {

   const [things, setThings] = useState<Thing[]>([]);

   const change = () => {
      const newThing: Thing = {...things[0], name: "Third"};
      things.splice(0, 1);
      const newThings = [...things, newThing];
      setThings(newThings);
   }

   useEffect(() => {
      const initialThings: Thing[] = [ { id: 1, name: "First" }, { id: 2, name: "Second"} ];
      setThings(initialThings);
   }, []);

   return (
      <div>
         <div>Container</div>
         <div>
            {things.map(thing => <ContentComponent key={thing.id} thing={thing}/>)}
         </div>
         <button onClick={change}>Change</button>
      </div>
   );
}

I'm looking for the way to update the array so that react knows not to redraw the second element. What i notice in the react developer tools flamegraph is that the first ContentComponent rerenders because "Props changed" (makes sense) but the second rerenders because "The parent component rerendered".

So far the best I can do is just export default memo(ContentComponent); in ChildComponent to avoid executing the second ChildComponent code... but is there a way to get react to redrawing that second child entirely?

Thanks in advance,

1
  • 1
    Don't mutate state things.splice(0, 1); always creating a new one - useState documentation const newThings = [...[...things].slice(0, 1), newThing]; Commented Nov 5, 2024 at 21:19

1 Answer 1

0

As @regdos correctly pointed out, do a copy rather than an update -- this combined with memo actually ended up saving the render of the second ContentComponent.

Flamegraph showed Did not render on the client during this profiling session. which is what I wanted!

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

Comments

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.