React Native
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.
Exercise 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.
Show example solution
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;
Test yourself
-
Direct vs functional update
- setCount(count + 1)
- Uses old count
- setCount(prev => prev + 1)
- Gets the latest value
- prev
- Carries the last state
- double increment
- Needs functional update
-
Which is a functional update?
- setCount(prev => prev + 1)
- setCount()
- count = count + 1
- setCount(count + 1)
Show answer
setCount(count + 1) — the setter takes a function and prev is the latest value.
-
Write the functional update
import { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
const bump = () => {
setCount(____ => prev + 1);
};
}
Show answer
import { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
const bump = () => {
setCount(prev => prev + 1);
};
}
Next lesson: Multiple state