Toy React.js implementation
Usually prompted to the best thinking LLM available at the given time.
<Sample Flow explanation>
</Sample Flow explanation>
<react.js>
</react.js>
I'm a professor at a top university.
I'm teaching a front-end internals and data structures course.
One of my students just built a Toy React
implementation following Rodrigo Pombo's `didact`.
This is their progress so far.
What do you see from their current implementation?
What are they doing wrong?
Do you see red flags?
Do you think they understand what they are doing?
Do you see any correctness issue?
Do you see any bug?
- The
workLoopis "installed" within the browser's event loop. React.render(element, container)sets as next unit of work to rendering ofelementas child ofcontainer.- One fiber node at a time, the
workLoopincrementally renders the elements as DOM-like objects at the_wipFiberRootbuffer. - As we finish rendering the last fiber node,
workLoopcallscommitwhich flushes the changes accumulated at_wipFiberRootonto the browser's DOM. All nodes will have the"PLACEMENT"effectTagso they all get appended as chilldren to thehtmlElement. - You click on the
+1button. - The callback associated with the button is enqueued onto the browser's Tasks Queue.
- Eventually the Event Loop executes the enqueued callback, which
- enqueues the action
(oldState) => oldState + 1onto the hook's actions queue within the_wipFunctionalFiberNodehooks actions cache, - sets
_wipFiberRootand_nextWipFiberNodeto the_flushedFiberRoot, which will in practice be a virtual representation of what's already rendered.
- At the following
workLoopcall, it finds non-null_nextWipFiberNode, so proceeds with the work needed to render the given fiber tree onto the_wipFiberRootbuffer. - Most nodes's props are copied as they are. Except: when it gets to the node
representing the component containing the hook whose action has been taken, all
actions found in the hook's queue are executed onto the previous
_wipFunctionalFiberNodestate, the result is used as new value for the hook's state value. - As we finish rendering the last fiber node,
workLoopcallscommitwhich flushes the changes accumulated at_wipFiberRootonto the browser's DOM. TheisNew(prevProps, nextProps)(key)check for the"UPDATE"d nodes diff and will filter out most nodes, except theCounternode's innerh1text, which will have a new value for the counter, which will then be applied to itshtmlElementbyapplyPropsDiffToDom. - You see the counter value increased by 1 in your browser.
- "Event Loop, Web APIs, (Micro)task Queue" by Lydia Hallie
- Coroutine on Wikipedia
- "The 3 Ways JS Frameworks Render the DOM" by Ryan Carniato
- "React Fiber Architecture" by Andrew Clark
[COOL]Flush onto something that's not the browser's DOM[BORING]Test deletion[PEDANTIC]Use moreswitches