DEV Community

Cover image for  How to useEffect vs componentDid/Will-unmount

How to useEffect vs componentDid/Will-unmount

Rohit Pratti on October 29, 2019

I was working on a project and I had to close out some modals, and realized there were both Class component modals and Functional component modals ...
Collapse
 
pallymore profile image
Yurui Zhang

Hi, in your code handleClick seems to depend on props.closeAddItemModal well first of all this.props probably does not work because it's a function component. Secondly if closeAddItemModal changes it probably will cause issues in this useEffect hook. It's probably better to add it as a dependency of the effect:

useEffect(() => {
  const handleClick = (e) => {
     // your handle click
  };

  document.addEventListener('mousedown', handleClick, false);
  document.addEventListener('keydown', handleClick, false);

  return () => {
    // remove event listeners here
  };
}, [props.closeAddItemModal]);
Collapse
 
brohittv profile image
Rohit Pratti

OHHH AMAZING THANK YOU GOOD CATCH!

Collapse
 
pallymore profile image
Yurui Zhang

I see you've updated the code. I would move the definition of handleClick to the body of that useEffect function (if it is not used elsewhere) so we won't be creating a new handleClick function on each render call. Also it's good to show that we are actually using the dependencies inside the hook directly.

If handleClick is also used in other places, an alternative method to this is to combine this with useCallback

const handleClick = useCallback(() => {
  // same handle click here
}, [props.closeAddItemModal]);

useEffect(() => {
  // same effect
  // different dependencies 
}, [handleClick]);

So if props.closeAddItemModal doesn't change we won't be creating new handleClick funcs and our useEffect hook will be safe.

I'd highly recommend this eslint plugin if you haven't used it npmjs.com/package/eslint-plugin-re...

Thread Thread
 
brohittv profile image
Rohit Pratti

its only used for this functions, so I just move it above the click listener? :o

Thread Thread
 
pallymore profile image
Yurui Zhang

Yea I would do that. So the function is within the same block scope created by the effect.

React could render multiple times (with or without any state / prop changes), it's better to keep dependencies and the code where they are used close.

Thread Thread
 
brohittv profile image
Rohit Pratti

So I made a Util file, and I imported the function and then and callingback to it inside the useEffect, and this works for all my modals except one modal which crashes when I open and close it too many times... any ideas why this could happen?