The foreword 0.
Some time ago, I found that I was not familiar with some knowledge points about React during the intern interview. Therefore, xiaobian spent a day to sort out the relevant knowledge points. This article records the finishing results of small series. React Hook, React lifecycle, and the difference between React function components and class components.
1. React Hook
The React website introduces Hook as follows:
Hook is a new feature in Act 16.8. It lets you use state and other React features without having to write a class.
In the first part of this article, we’ll take a look at hooks.
1.1 Why use Hook?
- Convenient in-app state logic between components: Without hooks, React provides a way to “attach” reusable behavior to components. Hooks enable the reuse of state logic without modifying the component structure
- Easy understanding of complex components: Hooks can make the internal state of components more predictable by breaking the interrelated parts of a component into smaller functions rather than enforcing a lifecycle partition.
- Unintelligible class: More React features can be used in non-class situations. Hooks provide a solution to the problem of adding state to a function component and calling its lifecycle.
1.2 Commonly used Hook sorting
useState()
: Adds some internals to the component by calling it from within the function componentstate
.useState()
Returns a pair of values: the current state and the function that updated it. Its usage is similar to the class componentthis.state()
State can only be declared once, whereas Hook can be used multiple times. The usage method is as follows:
import React, { 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>
);
}
Copy the code
useEffect()
: is an Effect Hook that gives function components the ability to manipulate side effects. It is the same as the class componentcomponentDidMount
,componentDidUpdate
, as well ascomponentWillUnmount
It serves the same purpose, but is consolidated into one API. When you useuseEffect
Tell React to run your side effect function after making DOM changes. The usage method is as follows:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() = > {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={()= > setCount(count + 1)}>
Click me
</button>
</div>
);
}
Copy the code
The function of this code is to change the title property of the document during the life cycle of componentDidMount.
useContext()
: a hook function that shares data across feet. This hook function followscontext
This property is related. forcontext
Properties, there must be a producer and a consumer of the context. Producer useReact.createContext()
Method to create the context; And consumers useuseContext
This hook function uses it. In a class component, use the context property, which needs to be in thecontextType
Pass in the name of the context property you want to use. Function components can be used as follows:
const themes = {
light: {
foreground: "# 000000".background: "#eeeeee"
},
dark: {
foreground: "#ffffff".background: "# 222222"}};const ThemeContext = React.createContext(themes.light);
function App() {
return (
<ThemeContext.Provider value={themes.dark}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background.color: theme.foreground}} >
I am styled by theme context!
</button>
);
}
Copy the code
useReducer()
:useState
The alternative to redux is similar to the one in Redux. The usage method is as follows:
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={()= > dispatch({type: 'decrement'})}>-</button>
<button onClick={()= > dispatch({type: 'increment'})}>+</button>
</>
);
}
Copy the code
useRef()
: Gets the component instance. Returns a mutable ref object. How to access DOM nodes in Ref or create React elements in render. A processing tool that has a third party operation outside of the declared cycle. The usage method is as follows:
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () = > {
// 'current' points to the text input element mounted to the DOM
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Copy the code
useMemo()
和useCallback()
:useMemo
Caching data,useCallback
Cache function.
1.3 Hook classification
Hooks can be divided into three categories:
- Enter useState, useContext, useReducer
- Output: useEffect, useMemo, and useCallback
- Other: useRef
1.4 Simulate the React life cycle with Hook
- ComponentDidMount: The second argument is an empty array to simulate componentDidMount
useEffect(() = > {
console.log('First render use')
},[])
Copy the code
- ComponentDidUpdate: Uses Ref to create an object that indicates whether it was called the first time, and then determines. There is no second argument to listen for all attributes; Listening for changes to multiple properties requires passing the properties as an array to the second parameter.
const mounted = useRef()
useEffect(() = > {
if(! mounted) { mounted =true
} else {
console.log('Component update usage')}})Copy the code
- ComponentWillUnmount: Component uninstallation needs to remove the Effect created by the subscription, timer resources. UseEffect returns a function to indicate that the component is dead.
useEffect(() = > {
return () = > {
console.log('Component is dead')}}, [])Copy the code
2. React Lifecycle
Broadly speaking, there are three stages: mount, render and unload. Details are as follows:
The important stages are:
- Mount stage: componentWillMount, componentDidMount, Render
- Running stage: componentWillUpdate, Render, componentDidUpdate
- Unloading stage: componentWillUnmount
In the new version of React, three phases have been removed and two phases added:
- Cancellation: componentWillMount, componentWillReceiveProps, componentWillUpdate
- New getDerivedStateFromProps and getSnapshotBeforeUpdate
React FunctionComponent and ClassComponent
- Class component definition functions need to bind this, function components do not
- Class components have a life cycle; function components do not
- Class components have a stateful state property and can conditionally render based on that property; function components do not
- The props of the function component is passed as an argument, so it cannot be changed. The props of a class component is passed as a property of the class, which can be changed at any time during execution.