ReactHustle

How to use LocalStorage in React by Using a Custom Hook

Jasser Mark Arioste

Jasser Mark Arioste

How to use LocalStorage in React by Using a Custom Hook

Hello, hustlers! In this tutorial, you'll learn how to use the localStorage API easily by using a custom hook from the usehooks-ts package. We'll also use typescript throughout the tutorial so you'll learn how to type objects when saving and pulling data from local storage.

Introduction #

Oftentimes, we need to use the localStorage API for our react application. What's the best way to use this with typescript? In my experience, one of the best ways is to use the usehooks-ts package.

What is usehooks-ts? #

The usehooks-ts package is an open-source, typescript-based, tree-shakable collection of useful react hooks that we can use in our react application. One of the most useful hooks it offers is the useLocalStorage and useReadLocalStorage hooks. These hooks allow use to read and write to the browser's localStorage API with ease.

Installing usehooks-ts library #

First, let's install usehooks-ts by using the following command.

# yarn
yarn add -D usehooks-ts

#npm
npm i usehooks-ts

Using useLocalStorage hook from usehooks-ts #

Now, we can use the useLocalStorage hook from any component. For example, suppose we save our theme data in the localStorage API:

// components/ToggleThemeButton.tsx
import { useLocalStorage } from "usehooks-ts";
export type Themes = "dark" | "light";
const ToggleThemeButton = () => {
  // usage is similar to the useSessionStorage hook.
  // We need to pass a key and an initial value.
  const [theme, setTheme] = useLocalStorage<Themes>("theme", "dark");
  return (
    <button
      onClick={() => {
        if (theme === "dark") {
          setTheme("light");
        } else {
          setTheme("dark");
        }
      }}
    >
      Toggle Theme
    </button>
  );
};
export default ToggleThemeButton;
12345678910111213141516171819202122

Using useReadLocalStorage #

In another component, we can use the useReadLocalStorage hook to pull data from local storage. By using useReadLocalStorage instead of useLocalStorage, we don't have to initialize the initial value because we're simply reading whatever is there.

// components/CurrentTheme.tsx
import { useReadLocalStorage } from "usehooks-ts";
import { Themes } from "./ToggleThemeButton";

const CurrentTheme = () => {
  const theme = useReadLocalStorage<Themes>("theme");
  return <div>CurrentTheme: {theme}</div>;
};
export default CurrentTheme;
123456789

Now, all that's left is to render both components:

import ToggleThemeButton from "../components/ToggleThemeButton";
import CurrentTheme from "../components/CurrentTheme";

const Home = () => {
  return (
    <div style={{ padding: 16 }}>
      <ToggleThemeButton />
      <CurrentTheme />
    </div>
  );
};

export default Home;
12345678910111213

Here's a demo, notice that when you refresh the page, it gets the current value from the local storage:

React Local Storage Tutorial Demo

Usage with Typescript #

To easily type the values we store and get from these hooks, all we have to do is to include a generic parameter as seen below.

export type Themes = "dark" | "light";
// we add <Themes> generic parameter same as when using other hooks like useState
const [theme, setTheme] = useLocalStorage<Themes>("theme", "dark");
...
const theme = useReadLocalStorage<Themes>("theme");
12345

I don't want to install a new dependency #

I understand that sometimes you don't want to introduce an external dependency from third-party libraries. Fortunately, usehooks-ts is open source and we can just simply copy the code right from the documentation:

Go to the following links to get the source code for these hooks:

Conclusion #

You learned how to use the localStorage API quickly and easily in a react application by using the usehooks-ts library.

Resources #

Credits: Image by Angie Agostino from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle