Skip to content Skip to sidebar Skip to footer

Componentwillunmount With React Useeffect Hook

How can the useEffect hook (or any other hook for that matter) be used to replicate componentWillUnmount? In a traditional class component I would do something like this: class Eff

Solution 1:

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

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

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]);

Solution 2:

useLayoutEffect() is your answer in 2021

useLayoutEffect(() => {
    return() => {
        // Your code here.
    }
}, [])

This is equivalent to ComponentWillUnmount.

99% of the time you want to use useEffect, but if you want to perform any actions before unmounting the DOM then you can use the code I provided.

Solution 3:

useEffect(() => {
  if (elements) {
    const cardNumberElement =
      elements.getElement('cardNumber') ||  // check if we already created an element
      elements.create('cardNumber', defaultInputStyles); // create if we did not
            
    cardNumberElement.mount('#numberInput');
  }
}, [elements]);

Post a Comment for "Componentwillunmount With React Useeffect Hook"