Functional updates

May 25, 2022

Sometimes you will need to update the state of your componnent based on its previsous state. To do so, you can use a functional update. In other words, you can pass a funtion to setState. This function takes the previous value as an argument and return an updated value - thus updating the state.

The counter example

In the following example, we are updating the count by adding or substracting one to its previous value

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

The object example

In the following example, we are updating the age of a person while keeping its name unchanged.

function People() {
    const [person, setPerson] = useState({ name: "Oli", age: 69 })

    const clickHandler = () => {
        setPerson(prevState => {
            return { ...prevState, age: 12 }
        })
    }

    return (
        <div>
            <p>Person name : {person.name}</p>
            <p>Person age : {person.age}</p>
            <button onClick={clickHandler}>Make me younger</button>
        </div>
    )
}

Profile picture

Written by Olivier Bonnet who lives and works in Montreal writing a blog that nobody reads 🤪...

© Bonneto 2024