CodeBlanks Logo Icon CodeBlanks

Previous state

Learn to derive new state from previous state.

Functional update

When deriving state from the current value, you use a functional update. You pass a function to the setter: setCount(prev => prev + 1). Here prev is the latest state value.

This matters especially when several updates fire in a row. setCount(count + 1) called twice uses the old count the second time; setCount(prev => prev + 1) always picks up the latest value.

You can name the parameter anything; the common choices are prev or previous. The key is passing a function to the setter.

When to use functional update?

If a single event triggers one update, direct assignment setCount(count + 1) is enough. But when a single event does several updates, functional update is required.

For example, to increment twice on one press: setCount(prev => prev + 1); setCount(prev => prev + 1);. The first call computes the new value, the second call uses it.

Another case: updating state inside setTimeout traps the old value via closure. Functional update also sidesteps this pitfall. So when in doubt, prefer functional update.

Practice Write a double increment

Write an App component. Define count with useState(0). Create a function called bump that calls setCount(prev => prev + 1) twice. Pressing the button should call bump and increment by two. Export the App function.

Starter code

App.js
import { useState } from 'react';
import { Text, TouchableOpacity } from 'react-native';

// write the double increment here

Sample solution

App.js
function App() {
  const [count, setCount] = useState(0);
  const bump = () => {
    setCount(prev => prev + 1);
    setCount(prev => prev + 1);
  };
  return (
    <TouchableOpacity onPress={bump}>
      <Text>{count}</Text>
    </TouchableOpacity>
  );
}
export default App;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Direct vs functional update

Term Meaning
setCount(count + 1) Uses old count
setCount(prev => prev + 1) Gets the latest value
prev Carries the last state
double increment Needs functional update

2 Which is a functional update?

  • setCount(prev => prev + 1)
  • setCount()
  • count = count + 1
  • setCount(count + 1) Correct answer

Explanation: the setter takes a function and prev is the latest value.

3 Write the functional update

Question
import { useState } from 'react';

function App() {
  const [count, setCount] = useState(0);
  const bump = () => {
    setCount(____ => prev + 1);
  };
}
Answer
import { useState } from 'react';

function App() {
  const [count, setCount] = useState(0);
  const bump = () => {
    setCount(prev => prev + 1);
  };
}

Explanation: prev carries the latest state value.

All lessons in Beginner