React tips: Update state the CORRECT way ✅

preview_player
Показать описание
🎓Why we should always use the updater function when updating state in React based on a previous value of that state.

📺[Watch next] React Optional Chaining with real world example:

If you liked this video please check out my udemy courses:
Gatsby JS, Prismic CMS & Netlify: Build RAPID sites in 2020

Gatsby JS & Firebase: Build HYBRID realtime + static sites

Gatsby JS: Build static sites with React Wordpress & GraphQL

React styled-components v5 (2020 edition)

Redux Saga (with React and Redux): Fast-track intro course

#reactjs #reacttips #reacthooks #reactstate #usestate #usestatehook #reactusestate
Рекомендации по теме
Комментарии
Автор

been looking for a good explaination on why to use prevState for a while and this is it!! :) thanks alot.

katjazenker
Автор

Great, looks like I made such errors earlier, thank you for make it clear

vyacheslavzgordan
Автор

Just discovered the "set" function pattern your showing here, can be really useful in some async scenarios!

It's a "gotcha" that you have to persist any events etc. if you'r just using it to capture a form value update for example. Since by the time your set lambda runs the event has been reused.
So I guess in those scenarios it's still preferable to just use the updateValue({name: e.target.value}) directly so you don't have to persist? Guess it's not a one size fits all here but...

Spagetti style function declaration withing function body is somewhat oldstyle no?
()=>{ function callback(){ function nestedCallback(){ }}} etc etc....
Aren't you suppose to use useCallback to handle that kind of scenario?

Thnx for sharing!

persv
Автор

Thank for this tip Tom, this is good to know.

hsdev
Автор

Thanks Tom, mad that the setCount function can either take a number or a function.

rorycawley
Автор

You are GOD! I had a similar issue. thank you thank you very much

vibhavrathee
Автор

How do I set state in a loop?
For example a loop that has a save button of every record on clicking would be saved true.

On setting the set state, it changes the state as saved to every single record instead of the one that was clicked.

hakan
Автор

How do we apply this if we’re working on a string and not a number?

rewky
Автор

How come setTimeout() pass the argument before it fires setCount?

jonathanyngfors