Jotai atomWithStorage

How to persist data in your application with Jotai, atomWithStorage might just be the solution you are looking for.
Tuesday, June 4, 2024

What is atomWithStorage?

Basically to put it simply atomWithStorage is a cool way for you the developer to persist data in your application, it’s a function that will automatically store the data of the atom in localStorage, sessionStorage for React or AsyncStorage for React Native.

That means you can persist your application data even if the user refreshes, closes or crashes the page or application and when the user comes back the data will still be there. The only way to remove the data is if the user manually clears their browser cache, local storage, session storage and cookies.

How to use atomWithStorage

To use atomWithStorage you need to import it from jotai/utils and then you can use it like you would use atom

import {useAtom} from "jotai";
import {atomWithStorage} from "jotai/utils";

const themeAtom = atomWithStorage("theme", "dark");
const userSettingsAtom = atomWithStorage("userSettings", 
  {language: "en", country: "us", accentColor: "blue"}
);

export default function Page() {
  const [theme, setTheme]=useAtom(themeAtom);
  const [userSettings, setUserSettings]=useAtom(userSettingsAtom);

  return (
    <div>
      <h1>Theme: {theme}</h1>
      <h1>User Settings</h1>
      <p>Language: {userSettings.language}</p>
      <p>Country: {userSettings.country}</p>
      <p>Accent Color: {userSettings.accentColor}</p>
    </div>
  );
}

As you see you can use atomWithStorage just like you would use atom, it really is as easy as that. It will automatically default to persisting the data in localStorage but you can also pass in a second argument to specify where you want to store the data.

const themeAtom = atomWithStorage("theme", "dark", sessionStorage);

Learn more about Jotai

You can find out more about why I love Jotai in my post Why I love Jotai and you can find the official documentation here

Wanna show support?

If you find my sporadic thoughts and ramblings helpful.
You can buy me a coffee if you feel like it.
It's not necessary but it's always appreciated. The content will always stay free regardless.