After years of using React, it still packs a surprise. Did you know you can update state while rendering?
Yep. From the docs:
whoa I legit did not think this worked 🤯
— Swizec Teller (@Swizec) June 23, 2023
time to replace a bunch of useEffect with update-state-during-render pic.twitter.com/Q7yq90kgnK
If you're like me, you wouldn't think to do this. You'd go with a useEffect
instead.
Updating state during render is unintuitive because every setState
triggers a re-render, but you're rendering right now. So how can you re-render while rendering without breaking something?
The clue comes in a different part of the docs, in the setState caveats section:
Calling the
set
function during rendering is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to store information from the previous renders.
It's a performance and UX optimization of sorts. Here's the difference.
With useEffect
A counter component that resets to a new number
when props change.
const Comp = ({ number }) => {
const [realNumber, setRealNumber] = useState(number)
useEffect(() => {
setRealNumber(number)
}, [number])
// ...
}
- Component renders with value in state
- Effect runs
- State updates
- Component re-renders with new state
You get a flash of stale state.
With update during render
A counter component that resets to a new number
when props change.
const Comp = ({ number }) => {
const [realNumber, setRealNumber] = useState(number)
const [prevProp, setPrevProp] = useState(number)
if (prevProp !== number) {
setRealNumber(number)
setPrevProp(number)
}
// ...
}
- Component starts rendering
- State updates
- React bails and re-starts render
- Component renders with new state
No flash of stale state, fewer spooky interaction effects between various useEffect
, a more stable experience for both you and the user. Yay.
Yes it does work
Here's a Codesandbox. I had to prove to myself that this works. Going to be useful in a few special cases like updating default values for form fields and menus that hide on scroll.
Cheers,
~Swizec
Continue reading about React can update state during render
Semantically similar articles hand-picked by GPT-4
- Update state during render, better explained
- How to use React Context effectively
- Declarative D3 transitions with React 16.3
- Declarative D3 charts with React 16.3
- useCallback is a code smell
Learned something new? Want to become a React expert?
Learning from tutorials is easy. You follow some steps, learn a smol lesson, and feel like you got dis 💪
Then comes the interview, a real world problem, or a question from the boss. Your mind goes blank. Shit, how does this work again ...
Happens to everyone. Building is harder than recognizing and the real world is a mess! Nothing fits in neat little boxes you learned about in tutorials.
That's where my emails come in – lessons from experience. Building production software :)
Leave your email and get the React email Series - a series of curated essays on building with React. Borne from experience, seasoned with over 12+ years of hands-on practice building the engineering side of growing SaaS companies.
Get Curated React Essays
Get a series of curated essays on React. Lessons and insights from building software for production. No bullshit.
Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.
Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.
Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.
Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev
Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization
Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections
Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog
Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️