Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between useEffect and useMemo

I'm trying to wrap my head around what exactly the useMemo() React hook is.

Suppose I have this useMemo:

const Foo = () => {
  const message = useMemo(() => {
    return readMessageFromDisk()
  }, [])

  return <p>{message}</p>
}

Isn't that exactly the same as using a useState() and useEffect() hook?

const MyComponent = () => {
  const [message, setMessage] = useState('')
  
  useEffect(() => {
    setMessage(readMessageFromDisk())
  }, [])

  return <p>{message}</p>
}

In both cases the useMemo and useEffect will only call if a dependency changes.

And if both snippes are the same: what is the benefit of useMemo?

Is it purely a shorthand notation for the above useEffect snippet. Or is there some other benefit of using useMemo?

like image 707
Dirk Hoekstra Avatar asked Nov 01 '25 06:11

Dirk Hoekstra


1 Answers

useEffect is used to run the block of code if the dependencies change. In general you will use this to run specific code on the component mounting and/or every time you're monitoring a specific prop or state change.

useMemo is used to calculate and return a value if the dependencies change. You will want to use this to memoize a complex calculation, e.g. filtering an array. This way you can choose to only calculate the filtered array every time the array changes (by putting it in the dependency array) instead of every render.

useMemo does the same thing as your useEffect example above except it has some additional performance benefits in the way it runs under the hood.

like image 175
Barry Michael Doyle Avatar answered Nov 03 '25 20:11

Barry Michael Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!