/** * Must react and react-dom 16.7 above */ import React, { useState, useEffect } from 'react' export default () => { const [name, setName] = useState('zhangsan') return ( <> <p>My Name is: {name}</p> <input type="text" value={name} onChange={e => setName(e.target.value)} /> </> ) }
This is a very, very simple demo, the first to use hooks, you must react and react-dom 16.7 above. Here we declare a function component, in contrast to previous class component, what he lacks is missing is this object. He did not this subject, there is no this.state, not the state itself has a function that contains a second, he can not have a life-cycle approach, which is the most obvious of several features, where we use hooks to stores the state
const [name, setName] = useState('zhangsan')
useEffect(() => { console.log('component update') return () => { console.log('unbind') } }, [])
function resolveDispatcher() { const dispatcher = ReactCurrentOwner.currentDispatcher; invariant( dispatcher !== null, 'Hooks can only be called inside the body of a function component.', ); return dispatcher; } export function useState<S>(initialState: (() => S) | S) { const dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); }
We see useState inside a dispatcher, the return value is useState dispatcher.useState. The dispatcher is called resolveDispatcher (). In the method resolveDispatcher see inside this dispatcher is obtained by ReactCurrentOwner.currentDispatcher. This is the follow-up when it comes to rendering will assign these things. Because react using the stage did not get any node. When createElement incoming object, not really rendering, not really created this instance. ReactCurrentOwner is a global class,
const ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: (null: null | Fiber), currentDispatcher: (null: null | Dispatcher), };
This is ReactCurrentOwner source code, very simple, is a global object. There are two properties, one is current, which is the current rendering nodes, the strength. currentDispatcher is the strength corresponding to the dispatcher. useEffect similar useState.