componentWillUnmount with React useEffect hook

后端 未结 1 1376
轮回少年
轮回少年 2021-02-03 17:24

How can the useEffect hook (or any other hook for that matter) be used to replicate componentWillUnmount?

In a traditional class component I wo

1条回答
  •  清歌不尽
    2021-02-03 17:26

    You can make use of useRef and store the props to be used within a closure such as render useEffect return callback method

    function Home(props) {
      const val = React.useRef();
      React.useEffect(
        () => {
          val.current = props;
        },
        [props]
      );
      React.useEffect(() => {
        return () => {
          console.log(props, val.current);
        };
      }, []);
      return 
    Home
    ; }

    DEMO

    However a better way is to pass on the second argument to useEffect so that the cleanup and initialisation happens on any change of desired props

    React.useEffect(() => {
      return () => {
        console.log(props.current);
      };
    }, [props.current]);
    

    0 讨论(0)
提交回复
热议问题