State as a snapshot
- React state behaves like a snapshot.
- It doesn’t replace a variable you already have, but triggers a rerender.
console.log(count); // 0
setCount(count + 1); // Request a re-render with 1
console.log(count); // Still 0!
-
Setting state triggers renders: calling setState triggers rendering.
-
Rendering takes a snapshot in time: a render captures a snapshot at a particular moment.
-
Rendering means React calls your function component. The JSX returned by the function is a snapshot of the UI. Its props, event handlers, and local variables all use the values calculated at that moment.
-
The rerendering process
- React calls the function.
- It returns a new JSX snapshot.
- React updates the screen, connected to that snapshot.
-
Example
<button onClick={() => { setNumber(number + 1); // number is 0, so React prepares to set it to 1 on the next render. setNumber(number + 1);// number is 0, so React prepares to set it to 1 on the next render. setNumber(number + 1);// number is 0, so React prepares to set it to 1 on the next render. }}>+3</button>setState only changes state for the next render.
setNumber ran three times, but number was always 0 inside the event handler. So it was set to 1 three times. When the event handler finishes, React rerenders with 1.
-
-
State over time
<button onClick={() => { setNumber(number + 5); alert(number); }}>+5</button>- number appears as 0.
<button onClick={() => {
setNumber(number + 5);
setTimeout(() => {
alert(number);
}, 3000);
}}>+5</button>
- What happens if we use setTimeout?
- A state variable never changes within a single render. Even if the event handler is asynchronous. Inside that render’s
onClick,numberkeeps its value even after the call. Its value was “fixed” when React called the component and took a UI snapshot.0setNumber(number + 5)- → We don’t have to worry about state changing while the code runs.
- What if we want to read the latest state before rerendering? Use a state updater function. (The prev → prev + 1 kind.)
Queueing a series of state updates
- React waits for all code in the event handler to run before processing state updates. → That’s why rerendering happens only after all the calls.
- Example: a waiter doesn’t run to the kitchen as soon as you start ordering. They wait until you’ve finished, made any changes, and other people have ordered, then go to the kitchen.
- → Benefit: you can update multiple state variables without triggering too many rerenders. The UI won’t update until the event handler and all its code finish.
- Batching makes React apps much faster and avoids dealing with half-finished renders.
State updater functions
- To update the same state variable multiple times before the next render, you can pass a function that calculates the next state from the preceding state in the queue. This is called an updater function, such as
n => n + 1.- When you pass it to the state setter:
- React queues this function to process after all the other code in the event handler has run.
- During the next render, React goes through the queue and provides the final updated state.
- When you pass it to the state setter:
export function getFinalState(baseState, queue) {
let finalState = baseState;
for(let i = 0 ; i < queue.length; i ++){
// Check whether queue[i] is a number
if(typeof(queue[i]) === 'number'){
finalState = queue[i]
}else {
const test = (n)=>{
finalstate = queue[i]
}
finalstate = test(queue[i](finalState))
}
}
// TODO: do something with the queue...
return finalState;
}
My answer was wrong.

The answer felt almost too simple: since it comes in as a function, no additional algorithm was needed.
export function getFinalState(baseState, queue) {
let finalState = baseState;
for (let update of queue) {
if (typeof update === 'function') {
// Apply the updater function.
finalState = update(finalState);
} else {
// Replace the next state.
finalState = update;
}
}
return finalState;
}
Updating Objects in React
React takes a snapshot of values and compares them with the previous ones.
But when does it take that snapshot? When the function is called.
When is the function called?
What prompted these questions was this:
React generally rerenders a component when the Props received from its parent or its internal State changes. React detects these changes through immutability. By copying object references, it can use shallow comparison, simply comparing references, to check whether something changed.
In JavaScript, objects are reference-type data stored in the memory heap. Changing an internal property leaves the reference unchanged. If you only change a particular property, React therefore considers the object unchanged and doesn’t rerender. To trigger a rerender, you need to tell React that the reference differs from the previous one.
Method 1 for changing references: Object.assign()
// Merge all object arguments after the first into it.
// Pass an empty object and the object to copy to return a new object.
const obj = { a: 1, b: 2 };
const obj2 = Object.assign({}, obj);
console.log(obj === obj2); // false
Method 2 for changing references: the spread operator.
// Put the properties into a new object.
const obj = { a: 1, b: 2 };
const obj2 = { ...obj };
console.log(obj === obj2); // false
Both approaches have limitations because they use shallow copies.
To address this:
const obj2 = { ...obj, b: { ...obj.b } };
console.log(obj.b === obj2.b); // false
Spreading twice solves it.
But with deeper objects, we’d have to keep changing the code, and the greater the depth, the easier it is to get confused.
That’s Why React Recommends Immer for Updating Objects.
Immutable object: An object whose state cannot change after creation. Because it cannot change, code using an immutable object can safely share it across multiple places. Code working with immutable objects doesn't need to consider effects on other consumers. Copying just a reference rather than the entire object also saves memory and improves performance.
How to copy just a reference:
const original = { name: "John", age: 30 };
const copy = original;
// copy shares the reference to original.
console.log(copy.name); // Prints "John"
// Changing original also affects copy.
original.name = "David";
console.log(copy.name); // Prints "David"
What is Immer? It helps maintain immutability when working with mutable objects.
How does Immer handle immutability?
Its core principles are Proxy and copy-on-write.
-
Proxy
Proxy, introduced in ES6, allows you to intercept operations on objects and functions to add custom behavior. It allows you to intercept operations on objects and functions to add custom behavior. Immer uses Proxy to intercept every operation on the object being worked on. The original object remains unchanged; all changes are handled through the Proxy and managed as a temporary draft state. This lets users write code as if directly modifying the original data, while the original data stays unchanged.The explanation alone doesn’t quite make it click for me…
-
Copy-on-write
Copy-on-write creates a copy of a data structure only when a change is needed. Immer follows this principle internally, copying only the portions that actually change. When a user modifies a draft object through a Proxy, Immer copies the modified portions and applies the new values to those copies. Because it doesn't copy the entire data structure every time, this can greatly improve memory usage and performance.
Here’s how these two work together.
- Draft Stage: Immer uses a Proxy to create a draft object based on the original object representing application state.
- Modifications: Developers can modify the draft directly. The Proxy catches every change without affecting the actual data.
- Produce: Once all changes are complete, Immer applies only the changed draft portions to copies of the actual data. Data is copied only at this point, using copy-on-write.
- New Immutable State: Finally, a new immutable state object containing the changes is created. It stays immutable until the next state update cycle.
Reference https://ui.toast.com/posts/ko_20220217
As an aside, I know structuredClone exists for deep copying. structuredClone is a JavaScript function for making deep copies of objects. It creates an entirely new object from the original, completely duplicating nested structures. It supports various built-in object types and data, producing an independent copy with the same structure as the original.
Features It produces a complete copy structurally identical to the original. The copying process doesn’t affect the original. It supports built-in types such as Map, Set, Date, and RegExp. It can copy objects with circular references.
I thought, “Then why not just use structuredClone?” Haha. But their purposes are different.
structuredClone aims to deep-copy data, while Immer's produce focuses on changing state while maintaining immutability. How they work: structuredClone creates an independent copy without modifying the original at all, while produce copies only parts of the original to create a new object containing the changes. Use cases: structuredClone is useful when you need to safely copy data; produce is especially useful in applications that manage state.
User Agents and Headers
This sprint, I learned about user agents, including that the user agent is sent along in the header.
I also learned about SSE, an alternative to sockets.
We also had an SSR error with useMediaQuery this sprint. I learned that sending the user agent to the server can help resolve this media-query issue.
What Gets Sent in Headers
Other things..
- toLocaleString: localizing dates and adding thousands separators.