In the previous lesson, we added a form to insert a new category.

However, when we reload the page, we’re presented that form again, because the category was not persisted anywhere.

Let’s do it, and save the category to local storage.

Tip: if you are unfamiliar with local storage, check this article I wrote about it.

How do we do that? We add a locaStorage.setItem() call into the addCategory method we defined previously:

const addCategory = category => {
  const updatedCategories = [...(categories || []), category]
  setCategories(updatedCategories)
  setShouldShowAddCategory(false)
  localStorage.setItem('categories', JSON.stringify(updatedCategories))
}

In addition to storing the data, we also need to retrieve it when the application starts.

To do that, we use the Effect hook, useEffect, on the App component:

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

//...
function App() {
  //..
  useEffect(() => {
    if (localStorage.getItem('categories')) {
      setCategories(localStorage.getItem('categories'))
    }

    if (!categories.length) {
      setShouldShowAddCategory(true)
    }
  })
  //...
}

If you add a console.log() in the useEffect() callback you’ll notice this function continuously runs, ad infinitum, because we are continuously call the setShouldShowAddCategory() method, which in turns causes a rerender. The useEffect() hook is called on component mount, and on component update. We need to add a second argument to useEffect, an empty array, to only run our effect on mount:

useEffect(() => {
  const categoriesInLocalStorage = JSON.parse(
    localStorage.getItem('categories')
  )

  if (categoriesInLocalStorage !== categories) {
    setCategories(categoriesInLocalStorage)
  }

  if (!categoriesInLocalStorage) {
    setShouldShowAddCategory(true)
  }
}, [])

Now when adding a category and then you reload the app, you won’t see the AddCategory component anymore, unless you clear the local storage manually using the browser console, using this line of JavaScript:

localStorage.setItem('categories', '')

See the app in the current state on CodeSandbox.


Go to the next lesson