How to use lifecycle methods with hooks in React?

后端 未结 4 2113
轮回少年
轮回少年 2020-12-13 11:11

I have gone through hooks introduced in react v16.7.0.

https://reactjs.org/docs/hooks-intro.html

So my understanding about hooks is we can play with state i

4条回答
  •  独厮守ぢ
    2020-12-13 11:35

    Here are examples for the most common lifecycles:

    componentDidMount

    Pass an empty array as the second argument to useEffect() to run only the callback on mount only.

    function Example() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        document.title = `You clicked ${count} times`;
      }, []); // Pass an empty array to run only callback on mount only.
    
      return (
        

    You clicked {count} times

    ); }

    componentDidUpdate (loose)

    By passing just the single argument into useEffect, it will run after every render. This is a loose equivalent because there's a slight difference here being componentDidUpdate will not run after the first render but this hooks version runs after every render.

    function Example() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        document.title = `You clicked ${count} times`;
      }); // No second argument, so run after every render.
    
      return (
        

    You clicked {count} times

    ); }

    componentDidUpdate (strict)

    The difference of this example with the example above is that the callback here would not run on initial render, strictly emulating the semantics of componentDidUpdate. This answer is by Tholle, all credit goes to him.

    function Example() {
      const [count, setCount] = useState(0);
    
      const firstUpdate = useRef(true);
      useLayoutEffect(() => {
        if (firstUpdate.current) {
          firstUpdate.current = false;
          return;
        }
    
        console.log('componentDidUpdate');
      });
    
      return (
        

    componentDidUpdate: {count} times

    ); }

    componentWillUnmount

    Return a callback in useEffect's callback argument and it will be called before unmounting.

    function Example() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        // Return a callback in useEffect and it will be called before unmounting.
        return () => {
          console.log('componentWillUnmount!');
        };
      }, []);
    
      return (
        

    You clicked {count} times

    ); }

    shouldComponentUpdate

    You can already achieve this on the component level using React.PureComponent or React.memo. For preventing rerendering of the child components, this example is taken from React docs:

    function Parent({ a, b }) {
      // Only re-rendered if `a` changes:
      const child1 = useMemo(() => , [a]);
      // Only re-rendered if `b` changes:
      const child2 = useMemo(() => , [b]);
      return (
        <>
          {child1}
          {child2}
        
      )
    }
    

    getDerivedStateFromProps

    Again, taken from the React docs

    function ScrollView({row}) {
      let [isScrollingDown, setIsScrollingDown] = useState(false);
      let [prevRow, setPrevRow] = useState(null);
    
      if (row !== prevRow) {
        // Row changed since last render. Update isScrollingDown.
        setIsScrollingDown(prevRow !== null && row > prevRow);
        setPrevRow(row);
      }
    
      return `Scrolling down: ${isScrollingDown}`;
    }
    

    getSnapshotBeforeUpdate

    No equivalent for hooks yet.

    componentDidCatch

    No equivalent for hooks yet.

提交回复
热议问题