DEV Community

How to build bulletproof react components

Jesco Wuester on April 12, 2020

Introduction React is a declarative framework. This means instead of describing what you need to change to get to the next state (which ...
Collapse
 
marklai1998 profile image
Mark Lai

you should use functional update when the new value is referencing the old one
That's react basic

setIsToggled((prevToggle)=>!prevToggle)
Collapse
 
eliseumds profile image
Eliseu Monar dos Santos • Edited

Not really. As a newcomer reading the docs, you find an example where setCount(count + 1) is used instead of a callback: reactjs.org/docs/hooks-state.html#.... Even though the API Reference indeed recommends using a callback, it's not very clear why.

Collapse
 
jsco profile image
Jesco Wuester

It's mostly for when the value updates extremely fast. That way even when 2 rerenders get batched together the value stays correct. I figured it wouldn't really matter for my example tho

Thread Thread
 
marklai1998 profile image
Mark Lai • Edited

That's what I meant to say
When I was a junior react developer, I always told to use callback whenever the new value is referencing the old one.
And indeed, doing simple setState it doesn't matter

But as the app grows, there are 2 cases that may cause the setState incorrect

  1. state update really fast
  2. multiple setState is called in different places

But I still tend to use callback whenever possible, because it's hard to justify when is okay to use the value straight away when the code is complex
Also when you are doing a large refactor, you can't rethink to make sure every single setState is safe

After the release of React hooks, I see more ppl write code that has a lot of side effect, useEffect everywhere, thus I think its more important to enforce this rule, otherwise ppl may fix a lot of silly bugs

Collapse
 
arhsim profile image
arhsim

Completely agree. In fact, in a function component the callback setup would also not help and the callbacks should be defined using a useCallback.

Collapse
 
sagar profile image
Sagar

Thanks, Jesco for the amazing article. After reading this article I realize that in our company application we've so many duplicate states. I'll try to minimize the use of states.

Collapse
 
uncleroastie profile image
Ron Male

Excellent article

Collapse
 
mkal1375 profile image
Mahdi Kalhor

👏🏻👏🏻👍🏻

Collapse
 
rhuanga10 profile image
riiniii

thank you! my react code renders often. guess there's much room for improvement!

Collapse
 
mhomol profile image
Mike Homol

This was a fantastic article.

Collapse
 
bernardbaker profile image
Bernard Baker

Great article 🌞. I was with one of svelte maintainers a while back. Great framework. Lots of potential.

Collapse
 
anthonybrown profile image
Tony Brown

💪👍👏🤙