Using useEffect() in React

useEffect() comes in very handy if you need to trigger an action or “side effect” from an object modification.

In the example below we have an array of names

const names = ["Alex", "Bob", "Sally"]

If we want to save the names array to localStorage every time it is modified we can implement useEffect()

import { useEffect } from "react"

function App() {
  // other setup code...
 
  useEffect(() => {
    localStorage.setItem("notes", JSON.stringify(names))
  },[names]) 
  // [names] is known as a dependency array, on every `names` change
  // `useEffect` will get executed

  // component rendering code.....
}

Leave a comment