Back to all blogs

Top 5 features developers love in CSS.

marraij

featured-work-image-03

Howdy Nerds, in this lesson, I learned about the useEffect hook.

The useEffect hook allows you to run custom code after React Renders (and re-renders your component to the DOM).

It accepts a call back function that ReactJS calls after the DOM updates.

Here’s the basic syntax:
React.useEffect(() => {})

Let’s take our form from our last lesson and see if we can make it store the user input into local storage with the useEffect hook:

import * as React from 'react'

function Greeting({initialName = ''}) {
  // 💣 delete this variable declaration and replace it with a React.useState call
  const [name, setName] = React.useState(initialName)
  function handleChange(event) {
    // 🐨 update the name here based on event.target.value
    setName(event.target.value)
  }

  return (
    <div>
      <form>
        <label htmlFor="name">Name: </label>
        <input onChange={handleChange} id="name" />
      </form>
      {name ? <strong>Hello {name}</strong> : 'Please type your name'}
    </div>
  )
}

function App() {
  return <Greeting initialName="Salym"/>
}

export default App

Let’s create our useEffect hook:

React.useEffect(() => {
window.localStorage.setItem('name', name)
})

When the application renders, it sets an item into local storage with the setItem() method with the key of ‘name’ and value of name; this value comes from our useState hook.

And you can also set it to run the callback function if a specific thing changes, like if our ‘name’ value updates, we call this an effect dependency:

useEffect(() => {
window.localStorage.setItem('name', name)
}, [name]); <-- effect dependency array

For us to see the effects of this hook, we need to get the item from local storage and set it as the default value for our state, like this:

const [name, setName] = useState(window.localStorage.getItem('name') || initialName)

 Lazy State Initialization

If we were to leave this component alone, it works fine; however, every time this component runs, it reads from localStorage, and reading from localStorage can hinder performance.

To avoid this, we pass a callback function to our useState initial value instead of the actual value:

const [name, setName] = useState(() => window.localStorage.getItem(‘name’) || initialName)

And now it only calls that function when the app renders the first time.

Check out the full code on codesandbox:

If you type something in the input field and reload the page, it will still be there because we are pulling that data from our localStorage. You can learn more about setItem() and getItem() from mozilla:

https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem

https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem

Custom Hooks

Let’s say you want to take this bit of logic and use it somewhere else in your program; well, you can do this with custom hooks.

A custom hook is just a function that uses hooks. These hooks can be built-in hooks or even other custom hooks.

const useLocalStorageState = ({initialValue = '', key}) => {
  const [state, setState] = React.useState(() => window.localStorage.getItem(key) || initialValue)

  React.useEffect(() => {
    window.localStorage.setItem(key, state)
  },[key, state])

  return [state, setState]
}

We take the logic that we want to reuse and put it inside a function called useLocalStorageState, which takes two props, initialValue and key. The key prop is for getting and setting an item from local storage.

And here’s how you use our new custom hook, it kind of looks like the useState hook.

const [name, setName] = useLocalStorageState('name', initialName)

In conclusion, I learned about the useEffect hook and how we can use it to store user input into local storage. And I also learned about custom hooks and how we can reuse logic.

Later Nerds

Share on social media

Let's make something great together.
© 2022 Marraij LLC.
All rights reserved.
Get in touch

4255 S Buckley Rd. Ste 107
Aurora, CO 80013

(720) 839-3166

info@marraij.com

Follow us on social media

Stay up to speed and get the last new and talk from Marraij