Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
946 views
in Technique[技术] by (71.8m points)

reactjs - How does React implement hooks so that they rely on call order

the React Hooks useState can attach local state to stateless functional component, for instance

const [name, setName] = useState('tom')
const [age, setAge] = useState(25)

I am wondering how the local state object tree looks like after executing the two line above? Rules of Hooks says something about how state is handled

React relies on the order in which Hooks are called

Or the local state is not object tree at all, just an array?

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hooks internally are implemented as a queue with each hook being represented by a node having the reference to the next one.

From the documentation:

There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.

The architecture would be similar to

{
  memoizedState: 'A',
  next: {
    memoizedState: 'B',
    next: {
      memoizedState: 'C',
      next: null
    }
  }
}

The schema of a single hook is as below. It can be found in the implementation

function createHook(): Hook {
  return {
    memoizedState: null,

    baseState: null,
    queue: null,
    baseUpdate: null,

    next: null,
  };
}

The key properties that let hooks behave the way they are are memoizedState and next.

Before each and every function Component invocation, prepareHooks() is gonna be called, where the current fiber and its first hook node in the hooks queue are gonna be stored in global variables. This way, any time we call a hook function (useXXX()) it would know in which context to run.

After the update finishHooks() will be called, where a reference for the first node in the hooks queue will be stored on the rendered fiber in the memoizedState property


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...