React Internals Deep Dive 5 - How does useState work internally?

preview_player
Показать описание
In this video, we'll dig into how useState() works, in a nutshell
1. each useState call creates a hook node in a linked list on Fiber,
2. each hook node has a update queue (linked list )holding the updates, also the current state
3. for the initial mount, useState() just sets things up and create a closure setState to trigger update
4. setState() calls creates update nodes in 2 and schedule a rerender
5. in rerender, update queue will be processed and current state is updated.

Hi I'm a JavaScript engineer who is not good at algorithms,
and currently practicing leetCode & BFE.dev. If you are interested, maybe we can learn together.
Рекомендации по теме
Комментарии
Автор

I just stumbled across this. Great and interesting series! Thanks so much for putting it together.

TheGRoques
Автор

great video. but i think there's a mistake in your memo pic and video, the queue head with lastRenderState=1, its "pending" should points to the update object without eager state(not evaluated yet, will evaluate in updateState while loop), then its next points to the update object with eager state. You can see in updateState while loop, react will always start with pending.next(var first = baseQueue.next) which is the first evaluated update object.

in mountState, the basic idea of assembling update circular link list is: the last update object becomes the pending object which always points to the first evaluated update object, previous object becomes the a normal link list member which points to the new pending object!


hope im not wrong. :D

hitkimi
Автор

The most beautiful implementation in mountState is
var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue);

address of currentlyRenderingFiber$1 will no change anymore after the bind, so every time we call setState it will put the pending.update to the fixed function fiberNode

weiway
Автор

and I'm wonder why they call this library ! it is a goddamn framework

mehdi-vlnn