DEV Community

Dayvster 🌊
Dayvster 🌊

Posted on • Originally published at dayvster.com

9

Jotai atomWithStorage

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs