The class components Hooks components
constructor useState
getDerivedStateFromProps Update function in useState
componentWillMount useLayoutEffect
shouldComponentUpdate useMemo
render The function itself
componentDidMount useEffect
componentDidUpdate useEffect
componentWillUnmount UseEffect is the function returned in useEffect
componentDidCatch UseEffect without
getDerivedStateFromError UseEffect without
// The function component does not need a constructor; we can initialize state by calling useState. If the calculation is expensive, you can also pass a function to useState. Const [num, UpdateNum] = useState(0) // getDerivedStateFromProps: In general, we don't need to use it, we can update the state during rendering to implement getDerivedStateFromProps. function ScrollView({row}) { let [isScrollingDown, setIsScrollingDown] = useState(false); let [prevRow, setPrevRow] = useState(null); if (row ! PrevRow == prevRow) {// Row has changed since last render. Update the isScrollingDown. setIsScrollingDown(prevRow ! == null && row > prevRow); setPrevRow(row); } return `Scrolling down: ${isScrollingDown}`; React will immediately exit the first render and re-run the component with the updated state to avoid too much performance cost. // componentWillMount useLayoutEffect => {console.log("useLayoutEffect: componentWillMount useLayoutEffect: componentWillMount useLayoutEffect ") The equivalent of componentWillMount "); Return () => {console.log("useLayoutEffect- return function ", new Date()); }; }, [number]); // shouldComponentUpdate: Const Button = React. Memo ((props) => {// Specific component}); // useMemo is equivalent to computed in VUE, useMemo Returned value: value useCallBack Returned value: Const getDoubleNum = useMemo(() => {console.log("useMemo", "getDoubleNum "); return 2 * number; }, [number]); Copy code Note: Memo is equivalent to PureComponent, which only compares props. Here you can also use useMemo to optimize each node. Render: This is the body of the function component itself. ComponentDidMount componentDidUpdate:. // componentDidMount useEffect(()=>{componentDidMount useEffect()=>{componentDidMount useEffect()=>{componentDidMount useEffect()=>{ Document. title = 'You clicked ${count} times'; Return () => {// required when count changes componentDidUpdate (prior to document.title =... }, [count]);}, [count], [count]); // Update the copy code only when count changes. Remember React waits for the browser to finish rendering the scene before delaying useEffect, thus making extra operations handy: Equivalent to useEffect return inside the cleanup function / / componentDidMount componentWillUnmount useEffect (() = > {/ / need in componentDidMount content of execution Return function cleanup() {// Need to do something in componentWillUnmount}}, []) Copy code componentDidCatch and getDerivedStateFromError: There are no Hook equivalents for these methods, but they will be added soon.Copy the code

Reference article: juejin.cn/post/684490…