⚛️🌲 React Holiday

We'll start from basics and get all the way to Suspense, Hooks, and advanced composition!
Each day is a 2-3 minute read with CodeSandbox and quick assignments.
Check out 2017 (below) for examples.

Day 10: setState is a food truck

December 10, 2017

When you set down with set state, you might think state is set immediately.

It isn’t.

this.setState({ count: 1 });
console.log(this.state.count); // <= Probably not what you expected

There’s a leak!

setState has a naming problem.

You’re right to think that setState sets state immediately. It’s in the name.
But only because it beats a more descriptive alternative like enqueueStateTransition

For a technical read of what’s going on, read the setState doc.

We’re gonna talk about hotdogs.

A fast-food mental model

Food trucks provide a great mental model for setState. Here are some attributes they share:


Food trucks act asynchronously—a big word for “I move on while they make food.”

I order.
I pay.
I step back and read twitter.
Other people order and pay.
5-10 minutes later someone hands me food.


Orders are queued but not a first-in, first-out queue.
Food trucks need to be fast so they batch and prioritize.


You like hot fries? Me too.
So when that fryer timer fires, fry orders get prioritized.

(say that 5 times fast)


While I imagine a chef decisively considering exactly how much Tabouli to garnish my “Lambda Lambda Lambda” with, it’s not how food trucks work.

Scott wipes his sweaty brow, looks ahead, see 5 orders of Lambda Lambda Lambda, and they get batched for quick processing.

What does this have to do with anything?

setState is a food truck.

Orders get queued.
Work gets batched and prioritized for speed.
And it all happens asynchronously.

On the next render, you can pick-up your piping hot Lambda Lambda Lambda and fries.

Tinker with it

Use the workspace below and play around with the state-setting illustration.


Written by chantastic.
Follow his nonsense on Twitter.