Home > Software design >  converting componentDidUpdate componentDidMount to hooks
converting componentDidUpdate componentDidMount to hooks

Time:07-30

Learning react by coding, trying to convert this code into hooks version, but i'm not getting any error and still code is not working ( class version works), just want to have some advice or help if i have converted it in right way or not?

english is not my mother language so could be mistakes.

class:

 componentDidMount() {
    this.updateCanvas();
    const img = this.refs.CameraImage;
    img.onload = this.updateCanvas.bind(this);
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    this.updateCanvas();
  }

  componentWillUnmount() {
    clearInterval(this.snapshotInterval);
  }

converted version:

useEffect(() => {
    updateCanvas();
    const img = CameraImage.current;
    img.onload = updateCanvas;

    return () => {
      img.onload = null;
    };
  });

CodePudding user response:

You are right according to React docs about hooks:

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
});

And an example of converted componentWillUnmount to hooks:

useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
});

And code would like this:

useEffect(() => {
    //   componentDidMount run once when the component is mounted
    this.updateCanvas();
    const img = refs.CameraImage;
    img.onload = updateCanvas;      

    // will be called on component unmount 
    return () => {
        clearInterval(this.snapshotInterval);
    }
})

CodePudding user response:

1 - you didn't pass an array into the useEffect Hook, so your component will continuously reload repeatedly.

2 - if you pass an empty array, then you are not watching any variables, and therefore it will only update the state on the first render, exactly like componentDidMount. in your case you are watching snapshot variable so add it as a dependency. So just change your code like this :

useEffect(() => {
    updateCanvas();
    const img = CameraImage.current;
    img.onload = updateCanvas;

    return () => {
      img.onload = null;
    };
  }, [snapshot]);
  • Related