React State Update
· 2 min read
Primitive Type Updates
Since primitive types are immutable by nature, it's perfectly fine to use the following approach to notify React of state changes:
const [count, setCount] = useState(0)
setState(1)
Object Updates (objects, Arrays)
Objects can be mutable, meaning the content of an object at the same memory location can be changed.
There are two main reasons why the official documentation recommends always using immutable approaches to update state, i.e., passing in a new copy of the object (deep copy):
-
Objects are passed by reference:
- Mutable approach: Direct mutation changes the position, but since the memory location remains the same, React cannot detect if the content has changed, so it won't trigger a re-render. We should use setPosition to register the state update.
const [position, setPosition] = useState({
x: 0,
y: 0
});
onPointerMove={e => {
position.x = e.clientX;
position.y = e.clientY;
}}- Immutable approach: Using setState to register state changes will correctly trigger re-renders.
const [position, setPosition] = useState({
x: 0,
y: 0
});
onPointerMove={e => {
setPosition({
x: e.clientX,
y: e.clientY
});
}} -
Avoid side effects: Using mutable data can lead to side effects, where modifying data might affect other parts of the code, causing errors or unpredictable behavior.