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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s