Are useMemo and useEffect callback good places to run code only at the birth and death of a React component?

87 views Asked by At

I want to hook into two lifecycle events of a React component. When it's born, and when it dies. When it's born, I want to load some data from the URL or local storage, and that data should not change no matter how many times the internal state of the component changes.

At the end of the component's life, when it's disposed of, I want to store some data in the local storage.

I thought of using useMemo() for the birth event. And I considered using a callback in an empty useEffect for the death event.

Have I chosen them correctly?

P.S. I want this that I'm creating a general list component. I want to load the initial filters from the URL or the local storage once. And when things change, I want to update the URL. And when the list is closed I want to store the latest filtering state in the local storage.

2

There are 2 answers

0
tao On

Use useEffect with an empty array of dependencies ([]):

React.useEffect(() => {
  // this code runs after the component is mounted

  return () => {
    // this code runs before the component is unmounted
  }
}, [])

React documentation for useEffect().


Notes:

  • the first argument of useEffect (the callback function) is run once, after the component was mounted (attached to DOM)
  • if the second argument (the dependency array) is an empty array, the callback will not be called again throughout the entire component lifecycle. If the array is not empty, the callback will be re-run whenever any of the contained dependencies changes value
  • if the callback function returns a function, the returned function will be run just before the component is unmounted
1
niko-cxvedadze On

I would prefer to use useEffect hook for both operation, i think you are meaning component mount and component unmount

for component mount you can use useEffect like that

useEffect(()=> {
   // this code will only run once when component mounts
}, [])

for component unmount you can still use useEffect but now you need to return callback function from useEffect which would only run on unmount when component dies

useEffect(()=> {
 
  return () => {
    // code written here only run when component dies (on component unmount) 
  }
}, [])

useMemo also is good way to optimise your to run only once when component loads and you can write like that

 const myLocalStorageValue = useMemo(() => localStorage.getItem("myvalue"),[])

if you pass an empty array to useMemo hook it would only run once, but remember the value of myLocalStorageValue variable would be what you return from arrow function passed in useMemo