Тёмный

React Hooks Closure Problems 

Ben Awad
Подписаться 496 тыс.
Просмотров 24 тыс.
50% 1

I go over an issue you may face when using React hooks that has to do with closures.
Code: codesandbox.io/s/angry-bush-4...
Links from video:reactjs.org/docs/hooks-faq.ht...
----
If you like cooking, checkout my side project: www.mysaffronapp.com/
----
Join the Discord: / discord
----
Patreon: / benawad
----
Follow Me Online Here:
Twitch: / benawad
GitHub: github.com/benawad
LinkedIn: / benawad
Instagram: / benawad97
Twitter: / benawad
#benawad
TikTok: / benawad ​

----
Follow me online: voidpet.com/benawad
#benawad

Наука

Опубликовано:

 

20 май 2019

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 56   
@someucmispersonicus3902
@someucmispersonicus3902 5 лет назад
This video single-handedly saved my sanity. I was making the freecodecamp's Pomodoro project with react and hooks, but for some reason it was off and now I know why.
@diegosabajo2182
@diegosabajo2182 2 года назад
very good explanation. thank you for your time
@srtlarx3625
@srtlarx3625 5 лет назад
Thanks Ben!
@bob7ii690
@bob7ii690 3 года назад
Great explanation. Thanks.
@user-pc4eg6rz2m
@user-pc4eg6rz2m 8 месяцев назад
Nice example and Nice description!!!
@ChrisAthanas
@ChrisAthanas 2 года назад
Excellent explanation
@hiepnh610
@hiepnh610 2 года назад
You saved my day. Thank you very much!!!!
@tomasznowak2032
@tomasznowak2032 2 года назад
Jesus, you are my hero after hours of torture with sse connection in react. It works, thank you!
@cutipets8706
@cutipets8706 2 года назад
I think you could use the previous value of count instead of doing it with Ref?
@antonals
@antonals Год назад
The best explanation of Closures in React
@caferrari
@caferrari 5 лет назад
You can cancel the last useeffect timeout.. see this example: repl.it/repls/TastyCulturedProfiler useEffect(() => { const tout = setTimeout(() => { alert(count); }, 3000); return () => clearTimeout(tout); }, [count]);
@tnchau1410
@tnchau1410 5 лет назад
I ran into something similar to this today in a react native app. Basically, I wanted to setParams on the navigation to some setState function returned from useState hook. I set the params in a useEffect with an empty deps array. If the setState fn is dependent upon the state, for example const [count, setCount] here. setCount(count + 1), count here is always the initial state, which is 0 I fixed the problem by using function setState: setCount(prev => prev + 1)
@MarcoLaspe
@MarcoLaspe 2 года назад
This is the way that should be used with functional components! Don't use useRef in this case.
@RikThePixel
@RikThePixel 2 года назад
The annoying thing is that there was like barely any documentation out there for this. Like I had to find some obscure, not even descriptive stack overflow article for this.
@dondev8005
@dondev8005 5 лет назад
Thanks ben. If anyone wants a more in-depth reading on this Dan Abramov wrote a great blog post.
@Deliverant
@Deliverant 5 лет назад
link?
@bawad
@bawad 5 лет назад
overreacted.io/a-complete-guide-to-useeffect/
@estranhokonsta
@estranhokonsta 5 лет назад
@@bawad You can find a similar solution to yours in another Abramov post: overreacted.io/making-setinterval-declarative-with-react-hooks/#refs-to-the-rescue To note the way he uses a custom hook and how he talks about the different 'state paradigms' of setInterval and React
@saadsurya3147
@saadsurya3147 4 года назад
You just saved my life Ben...
@ayoubalem865
@ayoubalem865 4 года назад
Conclusion: Whenever The SetState Method is Called The State Gets A New Reference, that means it doesn't have a new Value But we Create a New State with A New Value, So When We click On The Second Button The Event Handler Function Capture Tha reference of The Last State, So even if We Clicked Many Times In The First Button, When the Alert Displayed it Will Show The Value Of The State that The event Handler Captured its Reference.
@ankanbasu7381
@ankanbasu7381 2 года назад
instead of useRef, can't we use a normal object ? let countRef = { current: count }; ?
@DanteS7
@DanteS7 5 лет назад
Hey Ben, is there a way of having a generic event handler function with hooks? Something like this: handleChange = e => { const { name, value } = e.target this.setState({ [name]: value, }) }
@bawad
@bawad 5 лет назад
yeah and then you put a name on your input
@DanteS7
@DanteS7 5 лет назад
@@bawad how so? Only way I came up with was using a reducer but compared to the handleChange method that I normally use with classes it's too cumbersome
@bawad
@bawad 5 лет назад
@AbdullahAlMuzaki-pe6wb
@AbdullahAlMuzaki-pe6wb Год назад
thanks for sharing this 7 mins video, I thought it will be hours of debugging
@eolculnamo2
@eolculnamo2 3 года назад
First, I love React
@krunalchauhan5780
@krunalchauhan5780 3 года назад
I am working on AWS appsync but every time I get updated value don't know why it take old value even it display new value but when it update again it take first value😭 In class components it is working fine.
@anythingforweb
@anythingforweb 5 лет назад
I wonder what is the reason for the value being captured instead of referenced? Is it because react state is a new object every time setState is called?
@bawad
@bawad 5 лет назад
yes
@hardikmodi8234
@hardikmodi8234 5 лет назад
I have one problem with useReducer hook. whenever I dispatch an action it calls that action two times. I am not able to figure out why this is happening. Every time it calls the action twice.
@bawad
@bawad 5 лет назад
how are you triggering the action?
@hardikmodi8234
@hardikmodi8234 5 лет назад
@@bawad I had figured it out using browser debugger but still I am not able to understand the problem. It is because I had written reducer inside function. I just removed it from inside the function and declared it as const and it solves the problem. can you explain this please.
@priyajain6791
@priyajain6791 3 года назад
@@hardikmodi8234 Can you please show the sample code line ? Even I ran across the problem same as yours.
@locodev770
@locodev770 5 лет назад
good to know!, I think its a litle tricky, maybe the case with useEffect, could be solved with the cleanup function, returning a clearTimeout, and the other one with useCallback?, do you know another alternative?
@bawad
@bawad 5 лет назад
I think you might run into different issues, give it a try though
@DavidSmith-ef4eh
@DavidSmith-ef4eh 4 года назад
UseCallback wouldn't work. This was my first intuition as well, but turns out the only way to get the latest value is to save them as a reference.
@marcpeace204
@marcpeace204 4 года назад
@@bawad No Loco Dev is right. Your solution can be solved by casier means.
@diljeetsuri6040
@diljeetsuri6040 2 года назад
Can't we use a local variable in place of useRef ?
@jwoya
@jwoya 2 года назад
The variables within the App() function get recreated every time the function is called. With countRef = useRef(0), the countRef variable will still be recreated with every call, but it will always refer to the same object which React maintains in the background for you :) It is merely a "reference" to an object that lives beyond each App() function run.
@connor4161
@connor4161 2 года назад
couldn’t you just avoid this by having a dedicated useState/useEffect for handling this render? the timeout sets a “display state” equal to the current count state and then have a useEffect with a dependency array for the display state.
@xerxius5446
@xerxius5446 3 года назад
just make the state an object instead of a value, so the value is not copied const [ count, setCount ] = useState( { value: 0 } ) // use it like this count.value
@martinwinkler2604
@martinwinkler2604 2 года назад
This would solve nothing. If you keep the object reference the same and only update the value, then no update will ever trigger re-rendering, contradicting the core use of the useState hook. If all you need is a stable reference just take the useRef hook. If you need both use both.
@aharapu
@aharapu 3 года назад
I can see what is happening but I can't say I can understand the how. The closure never changed, and both "count as state" and "count as ref" seem to live in the same scope. What am I not getting?
@EscherSketcher
@EscherSketcher 3 года назад
You have to understood how javascript handles copy by value, and point by reference. Count as State is making a "copy" of count's value at that time. Count as Ref is a "reference", so it is pointing to the same count variable. And whatever it may be later on, it still points to it in memory.
@elik3765
@elik3765 Год назад
all these explanations of stale state/stale closure are at the level of here we are witnessing the problem, no clue why it's happening (mentioning jargon doesn't really explain why) and here is the solution, which is basically at this point magic. I'd really apprecite explanation at the level of call stack, exectution content, event loop etc...
@ivanserenko6805
@ivanserenko6805 3 года назад
not a bug but a feature
@nazarm6215
@nazarm6215 5 лет назад
This is not a hooks problem, that's JavaScript.
@calebclawrence
@calebclawrence 4 года назад
Well it is but people didn't deal with this as much when working with class component so I a sense it is a hooks problem
@gwapster13
@gwapster13 4 года назад
@@calebclawrence It is not a "problem" with Javascript, nor with Hooks. It is just the way React and its Hooks work, the useState hook is not meant to establish a closure.
@shubhamdhingra6089
@shubhamdhingra6089 3 года назад
@@gwapster13 Learnt it the hard way. Wasted 2 days on this but at least I won't be making this error anytime soon.
@jeffreydelossantos8667
@jeffreydelossantos8667 3 года назад
yes I think its somehow a Javascript problem, and we can solve it with that way: const referCount = {count: 0}; function App() { const [count, setCount] = useState(0); useEffect(() => { referCount.count = count; }, [count]); function handleAlertClick() { setTimeout(() => { alert("You clicked on: " + referCount.count); }, 3000); } return ( You clicked {count} times setCount(count + 1)}>Click me Show alert ); } but this is a not so clean way to solve it, this video has a better solution for React components
@andreivilla9009
@andreivilla9009 3 года назад
I dislike React Hooks for this particular reason
Далее
React Hooks useMemo Tutorial
11:21
Просмотров 78 тыс.
Stray Kids <ATE> Mashup Video
02:17
Просмотров 912 тыс.
Redux or Context in React
6:16
Просмотров 98 тыс.
React Hooks useRef Tutorial
9:22
Просмотров 97 тыс.
React Hooks: Advanced Hooks
20:52
Просмотров 87 тыс.
React Hooks useContext Tutorial (Storing a User)
11:38
Просмотров 357 тыс.
React Hooks useLayoutEffect Tutorial
10:22
Просмотров 44 тыс.
React hooks : UseState creates a closure
20:08
Fun with React Hooks - Michael Jackson and Ryan Florence
1:02:51
React Typescript Tutorial
23:33
Просмотров 574 тыс.
ПОКУПКА ТЕЛЕФОНА С АВИТО?🤭
1:00
Собери ПК и Получи 10,000₽
1:00
Просмотров 2,3 млн