Preface
When we first learn React, most of us will choose to take a look at React's official documentation to see what it is and how to use it. But I am very curious that the first complete component I learned in the document is the Class component, but in actual work we see that the components declared in the project are all displayed in the form of functions. So a small question caused me to explore new knowledge. It turns out that as the project develops, components will be filled with more and more complex state logic and side effects. Logics that appear in pairs, such as event monitoring and removal, are split into different methods, and there are many complete If unrelated codes are combined together, many bugs will be generated. Even when the project is packaged, Class cannot be compressed well, and will cause hot reloading to be unstable, etc... Facebook engineers thought of a good alternative to introduce an API to allow function components to have the same status as Class components. Management capabilities and complete life cycle functions. He is Hook. But we can still continue to use Class components.
What is Hook
Hook is a new feature of React 16.8. Its purpose is to allow developers to use state to implement component life cycle, Ref and other React features without writing Class.
for example:
Principle of hooks
Recommend a blog written by a blogger to implement minimalist useState: React Technology Revealed, which describes the principle of the underlying implementation of react useState. Then cooperate with GitHub - acdlite/react: A declarative, efficient, and flexible JavaScript library for building user interfaces. React source code to try to understand the Hook concept.
Use of hooks
- Using StateHook
For example, generally we define a state variable
const [count , setCount] = useState(initValue);
initValue: is to set the initial value
There are two situations when using setCount
setCount( newValue ); //When the parameter is a non-function value, directly specify the new status value
setCount( oldValue =>{ … return newValue} ) //When the parameter is a function, receive the original status value and return the new status value through the function
- Using ReducerHook
An upgraded version of useState. In some scenarios, useRucer is more suitable than useSate. For example, the state logic is complex and contains multiple sub-values, or the next state depends on the previous state, etc. The principle is similar to redux, requiring reducer, action, and dispatherinitValue: setting the initial value
- Using EffectHook
You can think of useEffect as a combination of the following three functions
componentDidMount( );
componentDidUpdate( );
componentWillUnmount( );
useEffect( ( )=>{
}) ; //监听所有useState变量的变化
useEffect( ( )=>{
return ( ) => {
//相当于componentWillUnmount }
}) ;
useEffect( ()=>{
} , [ ] ) ; //不监听任何变量 且函数只会在第一次 render( ) 后执行
useEffect( ( )=>{
} , [name,list]) ; //监听name list变量的变化
- Use RefHook
const inputEL = useRef( ); 声明一个标记容器
<input type="text" ref={
inputEL } />
inputEL.current.focus( );
inputEL.current.blur( );
- Use CallbackHook
Use useCallback to cache the function. When the component is updated again (the function component is re-rendered), the cached function or the new function will be selected based on whether the incoming dependencies have changed. , the comparison method is shallow comparison object.is( ).
After we wrap the function with useCallback, only when Text and isKey change in the parent component, a new handleIneerHTML instance will be created, and the child component will follow reRender.
- When using MemoHook
Be careful to distinguish the difference between useMemo and React.memo()
If the second parameter of useMemo(fn, arr) matches and its value changes, it will be executed multiple times, otherwise it will only be executed once. If it is an empty array [], fn will only be executed once.
useMemo and useCallback are two APIs provided by reactHook, used to cache data and optimize performance; both receive the same parameters, the first parameter represents a callback function, and the second represents dependent data.
Common function: When the dependent data changes, the callback function passed in will be called to recalculate the results, acting as a cache.
The difference between the two: the result cached by useMemo is the value returned in the callback function. It is mainly used to cache the value of the calculation result. Application scenarios such as the state that needs to be calculated
The result of useCallback cache is a function, which is mainly used for caching functions. Application scenarios such as functions that need to be cached, because every time any state of a functional component changes, it will trigger an update of the entire component. Some functions do not need to be updated. At this time, It should be cached to improve performance and reduce waste of resources; in addition, it should be noted that useCallback should be used in conjunction with React.memo. If one is missing, the performance may not increase but decrease.
- Use ContextHook
We want to implement a button to change the text color of other componentsUsing context for data communication, we need to let the context component handle all required Use components that share data for wrapping. The props.childRender() here uses a slot-like syntax. What is passed in from the outer parent component is a jsx syntax, which contains the child components that need to share data< /span>This is the shared data obtained by the sub-component through useContext
TextComponent component
Buttons component
- Custom Hook
A program will have multiple components, in which the same function may be called. In order to avoid calling this function every time, we have to put it in our own component. The same logic is written repeatedly, so we need to extract this logic and call it as a public Hook, such as the custom Hook used in the project to monitor window size changes