Getting started with Jotai

Managing state in React applications can sometimes feel more complex than it needs to be. If you’ve been looking for a lightweight and straightforward solution, Jotai might be the answer you’re searching for. As a global state management library, Jotai, embraces an atomic approach that simplifies state handling at all scale levels—from the simplest to the most demanding enterprise applications. In this article, we delve into how Jotai can streamline your state management in React, providing a minimal API with TypeScript support for an improved development workflow.

What is Jotai and How Does It Enhance React Development?

Jotai takes its inspiration from the concept of atoms in physics—fundamental units that can combine to form structures. In Jotai, each atom represents a piece of state. You can have primitive atoms or derived atoms that rely on other atoms to determine their value. This makes state management both flexible and efficient, as your components only re-render when their specific atoms change, preventing unnecessary updates.

Let’s explore how Jotai stands out for developers and can potentially revolutionize your React projects.

Installation and Setup

To get started with Jotai, install it as a dependency in your project:

npm install jotai
# or
yarn add jotai

For a smoother experience when using fast-refresh with React, consider adding an optional SWC or Babel plugin. This enhances your development experience by retaining your state when editing components, allowing for a snappy update flow.

Creating Atoms with Jotai

Atoms are the building blocks of your state in Jotai. Creating a new atom is straightforward and can store any value type—from strings and numbers to more complex objects.

Primitive Atoms

A primitive atom is a basic atom that holds a value. Here’s how to create one:

import { atom } from 'jotai'

const countAtom = atom(0)

In the example above, countAtom holds a number with an initial value of 0.

Derived Atoms

Derived atoms can compute their value based on other atoms. They’re like selectors in other state management libraries. Here’s an example:

const doubleCountAtom = atom((get) => get(countAtom) * 2)

doubleCountAtom will always be double the value of countAtom.

Using Atoms in Components

Jotai provides the useAtom hook to read and update atom values within your React components. For more granular control, you can also use useAtomValue for read-only purposes and useSetAtom for write-only scenarios.

The useAtom Hook

The useAtom hook provides an elegant API to both read from and write to an atom:

import { useAtom } from 'jotai'

function Counter() {
  const [count, setCount] = useAtom(countAtom)

  return (
      <p>Count: {count}</p>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>

This hook returns a pair with the current value and an updater function.

Server-Side Rendering with Jotai

For projects utilizing Next.js or Gatsby, you’ll need to add Jotai’s Provider to the root of your application to support server-side rendering seamlessly.

import { Provider } from 'jotai'

function MyApp({ Component, pageProps }) {
  return (
      <Component {...pageProps} />

This encapsulates your state management for each request, avoiding global state issues across different server-rendered pages.

Leveraging Utilities and Extensions

Jotai is impressive out-of-the-box, but it also offers utilities and extensions to augment its capabilities:

Persisting State

The atomWithStorage utility allows you to persist state changes to localStorage, making it effortless to maintain state between browser sessions.

Integrating with Other Libraries

Jotai’s extension packages provide compatibility with libraries like XState, Immer, Relay, and more, creating a more versatile ecosystem around your state management needs.

Handling Asynchronous Actions

You can use Jotai atoms with async functions, allowing for more complex state changes or data fetching:

const fetchUserAtom = atom(async (get) => {
  // Fetch logic here

Jotai intuitively handles asynchronous actions within atoms.

Conclusion: Is Jotai the Right Fit for Your Project?

Wrapping up, Jotai offers a refreshingly minimalist API for state management in your React applications. Its suitability for TypeScript projects, avoidance of unnecessary re-renders, and scalable approach from simple useState replacements to complex application state management make it an attractive library for developers.

It doesn’t stop at the basics, though. With its utilities and extensions, Jotai can be tailored to fit a variety of application needs, whether that’s persistence, compatibility with other state libraries, or advanced asynchronous handling.

If you’re inspired to simplify your React state management, consider giving Jotai a try in your next project. Visit the Jotai GitHub repository to explore its possibilities, and start enjoying a more streamlined state management experience.