import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In the above example whenever setCount(count + 1)
is invoked a re-render happens. I am curious to learn the flow.
I tried looking into the source code. I could not find any reference of useState
or other hooks at github.com/facebook/react.
I installed react@next
via npm i react@next
and found the following at node_modules/react/cjs/react.development.js
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
On tracing back for dispatcher.useState()
, I could only find the following ...
function resolveDispatcher() {
var dispatcher = ReactCurrentOwner.currentDispatcher;
!(dispatcher !== null) ? invariant(false, 'Hooks can only be called inside the body of a function component.') : void 0;
return dispatcher;
}
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null,
currentDispatcher: null
};
I wonder where can I find dispatcher.useState()
implementation and learn how it triggers re-render when setState
setCount
is invoked.
Any pointer would be helpful.
Thanks!
fiber
so said Reacts core algorithm. They describe it as,React Fiber is an ongoing reimplementation of React's core algorithm.
github.com/acdlite/react-fiber-architecture I would believeuserState
-creates Object and pointer infiber
an when ever it value changes it triggers re-render. This is just a guess but I would expect something similiar to this. – Hereditary