Learning useEffect: persistent state in React

Hi, in this post we are going to lear about the useEffect in React, this method is part of the special functions that React handle in “hooks“.

useEffect

Allow us to run some custom code after React renders and re-renders our component into the DOM.

useEffect accepts a callback function which React will call after the DOM has been updated.

useEffect format Example:

// React hook method called useEffect
useEffect(() => { // callback function

  // Our side-effect code here.
  // we can make HTTP requests or interact with browser APIs.

})

Example:

Let’s use localStorage (allow to save key/value pairs in the browser) and useEffect to save a persistent value for example our name.

1.- We have our Greeting component that receive a initialName prop.

2.- We are declaring initial state (useState) where we are saying give me the name value that is save it at localStorage if name have a value or give me the initialName value if initialName have a value to initialize the component state.

3.- useEffect will be executed the callback function … ( ) => { } every-time that the component get render, inn this case the component is rendering because the name is changing.

4.- Method that is triggered on the input every-time that user write.

5.- Rendering Html with values.

// Dependencies
import React, {useState, useEffect} from 'react'

// 1.- Greeting Component
function Greeting({initialName = ''}) { 
  // 2.- Initial state using useState hook
  const [name, setName] = useState(
    window.localStorage.getItem('name') ?? initialName,
  )
  
  // 3.- Every-time that name is changing then execute the callback to 
  // save that value into the localStorage
  useEffect(() => {
    window.localStorage.setItem('name', name)
  })

  // 4.- Method that is triggered on the input every-time that user 
  // write something on the input
  function handleChange(event) {
    setName(event.target.value)
  }

 // 5.- Rendering Html with values
  return (
    <div>
      <form>
        <label htmlFor="name">Name: </label>
        <input value={name} onChange={handleChange} id="name" />
      </form>
      {name ? <strong>Hello {name}</strong> : 'Please type your name'}
    </div>
  )
}

function App() {
  return <Greeting />
}

export default App

View:

Initial value is coming from localStorage that also is empty

Then if I write my name into the input then localStorage is going to save my name (because the useEffect callback)

Then if I refresh the page the name will be there (persistent) at the input and at the localStorage.

Here a React Hook flow diagram

By Cristina Rojas.