5

I have a component with an array of objects in local state:

    const [myState, setState] = useState<SomeObjectType[]>([]);

I can update a single object in that array by making a copy of the entire array and then update the property of the single object I wish to update:

OPTION 1


    const state = [...myState];
    state[id].description = description;
    setState(state);

Or I can use map:

OPTION 2


  const newState = talkingPoints.map(el => {
      // 👇️ if id equals, update description property
      if (el.id === id) {
        return {...el, description};
      }

      // 👇️ otherwise return as is
      return el;
    });

    setData(newState);

Or can I do this (since I am 100% certain the id exists in the array)?

OPTION 3

  const handleUpdate = () => {
    setState(prevState => ({
      ...prevState,
      prevState[id].description = description
    }))
  }

For cases where I am not 100% certain I can use map and find it:

OPTION 4

  const handleUpdate = () => {
    setState(prevState => ({
      myState: prevState.myState.map(el => el.id === id ? { ...el, description } : el)
    }))
  }

What is recommended/best practice? Is Option 1 (fully array copy) faster than using map?

1 Answer 1

7

Option 3 and opntion 4 are incorrect, the prevState/myState is an array and you are returning an object, this will surely cause error in typescript. As to option 1 and 2, they only differ between declaritive and imperitive way of programming. And declaritive programming makes more readable code.

On option 1:

const newState = [...myState];
newState[index].description = "new desc"; 
// Access index position as opposed to id
// since the item's position may not align with it's id
setState(newState );

On option 2 with map function, it can be written as follows:

setState(myState.map(item => item.id === id ? {...item, item.description: "new desc"} : item))

In conclusion, use map/filter is more preferable to update array.

Here's sandbox to compare option 1 and 2

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.