useEffectThe life cycle that can be substituted iscomponentDidMount.componentWillUnMountcomponentDidUpdate

useuseEffectcompletecomponentDidMountThe effect of

function AComponent() {
    useEffect((a)= > {
        // TODO} []); }Copy the code

UseEffect is only called for componentDidMount and componentWillUnMount when the second argument is []

ComponentWillUnMount calls the callback returned by the first argument

useuseEffectcompletecomponentDidUpdateThe effect of

function AComponent({source}) {
    useEffect((a)= > {
        const subscription = source.subscribe();
        // TODO
        return (a)= > {
          subscription.unsubscribe();
        };
    }, [source]); // when the source changes, it is executed once
}
Copy the code

forceUpdate

function AComponent() {
    const [ignored, forceUpdate] = useReducer(x= > x + 1.0);

    function handleClick() { forceUpdate(); }}Copy the code

getDerivedStateFromProps

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}`;
}
Copy the code

Get beforepropsstate

function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  return <h1>Now: {count}, before: {prevCount}</h1>;
}

function usePrevious(value) {
  const ref = useRef();
  useEffect((a)= > {
    ref.current = value;
  });
  return ref.current;
}
Copy the code