Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React setState function

What is the difference between these two state updating functions and what is the recommended approach? Both functions work fine in my application.

Option 1

const [profile, setProfile] = useState<{name: string, age: number}>({
    name: 'John Doe',
    age: 28,
  });

setProfile((prevState) => {
    return {
      ...prevState,
      age: profile.age + 100,
    }
  });

Option 2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [profile, setProfile] = useState<{name: string, age: number}>({
    name: 'John Doe',
    age: 28,
  });

setProfile({
    ...profile,
    age: profile.age + 100,
  });

>Solution :

Normally each time you want to update your state based on your previous state you should use the functional way of updating the state. It makes sure that the current state you are passing in, is the ‘last version’ one.

When you want to set a state based on a different value, not depending on previous state, you can set the state directly without using the functional update.

It is pretty well explained with examples in the documentation:

https://reactjs.org/docs/hooks-reference.html#usestate

the documentation includes this great example:

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
}

Note that unlike setState in a class component, useState doesn’t merge update, Also from the documentation:

Unlike the setState method found in class components, useState does
not automatically merge update objects. You can replicate this
behavior by combining the function updater form with object spread
syntax:

const [state, setState] = useState({});
setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

Option 2 will work in most cases because you rarely have a change of state appearing before another change of state, but it can happen in more complex cases or using useEffect or setTimeout functions and in this case the functional update is compulsory.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading