State Management with Jotai — React and TypeScript ready library — World of Atoms

Maciej Poppek
5 min readAug 5, 2024

--

State management in modern web applications can be a daunting task, especially as your app grows in complexity. React, a popular library for building user interfaces, provides built-in tools like useState, useContext and useReducer for managing state. However, as your state needs grow, these tools might become insufficient. This is where Jotai comes in — a state management library that promises to make state management both easy and enjoyable.

What is Jotai?

Jotai, which means “atomic” in Japanese, provides a simple and flexible way to manage state in React applications. It uses a minimalistic API that revolves around atoms, making state management both intuitive and powerful. Atoms are units of state, and components can read from and write to these atoms. Unlike some other state management libraries, Jotai leverages React’s hooks and provides a more granular way to manage state.

Why Jotai?

  1. Simplicity and Ease of Use: Jotai’s API is straightforward. You create atoms for your state and use hooks to interact with them. This simplicity makes it easy to get started with Jotai and integrate it into existing projects.
  2. Granular State Management: With Jotai, you can create state atoms for specific pieces of state, avoiding the pitfalls of having a single, monolithic state object. This granularity leads to better performance and more maintainable code.
  3. TypeScript Support: Jotai has excellent TypeScript support, making it easier to catch errors at compile time and providing a better developer experience.
  4. Integration with React: Jotai works seamlessly with React’s ecosystem, including concurrent mode and server-side rendering. It feels like a natural extension of React’s own state management hooks.

Getting Started with Jotai

Let’s dive into some code to see how easy it is to use Jotai for state management. We’ll create a simple application that manages a counter, the creation of tasks, and a list of tasks.

Setting Up the Project

First, ensure you have a React project set up with TypeScript. If you don’t, you can create one using Create React App:

npx create-react-app jotai-demo --template typescript
cd jotai-demo

Next, install Jotai:

npm install jotai

Creating Atoms

Atoms are the core of Jotai’s state management. They represent pieces of state that components can subscribe to and update.

// src/model/atoms.ts
import { atom } from 'jotai';

interface Task {
name: string;
}

export const countAtom = atom(0);
export const tasksAtom = atom<Task[]>([]);

In this example, we create two atoms: one for a counter (countAtom) and another for a list of tasks (tasksAtom).

Using Atoms in Components

Now, let’s create components that interact with these atoms.

// src/Counter.tsx
import React from 'react';
import { useAtom } from 'jotai';
import { countAtom } from './model/atoms';

export const Counter: React.FC = () => {
const [count, setCount] = useAtom(countAtom);

return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
};

In the Counter component, we use the useAtom hook to read and update the countAtom. This hook provides the current value of the atom and a setter function to update its value.

// src/CreateTask.tsx
import React, { useState } from 'react';
import { useSetAtom } from 'jotai';
import { tasksAtom } from './model/atoms';

export const CreateTask: React.FC = () => {
const setTasks = useSetAtom(tasksAtom);
const [task, setTask] = useState('');

const addTask = () => {
setTasks((prev) => [...prev, {
name: task,
}]);
setTask('');
};

return (
<div>
<h2>Create a new task</h2>
<input
type="text"
value={task}
onChange={(e) => setTask(e.target.value)}
/>
<button onClick={addTask}>Add Task</button>
</div>
);
};

In the CreateTask component, we use useSetAtom to interact with the tasksAtom — since, we don’t have to read current atom’s state, we can just use setter hook — it simplifies our code even more. We also use React’s local state (useState) for the input field.

Now let’s create a component that displays a list of the created tasks.

// src/TasksList.tsx
import React, { useState } from 'react';
import { useAtomValue } from 'jotai';
import { tasksAtom } from './model/atoms';

export const TasksList: React.FC = () => {
const tasksList = useAtomValue(tasksAtom);

return (
<div>
<h2>Tasks List</h2>
<ul>
{tasks.map((task, index) => (
<li key={index}>{task.name}</li>
))}
</ul>
</div>
);
};

In the TasksList component, we use useAtomValue to read the data stored in the tasksAtom. Since we will not manipulate the data, we can just use the getter hook.

Putting It All Together

Finally, we can put these components together in our main App component.

// src/App.tsx
import React from 'react';
import { Counter } from './Counter';
import { CreateTask } from './CreateTask';
import { TasksList } from './TasksList';

const App: React.FC = () => {
return (
<div>
<Counter />
<CreateTask />
<TasksList />
</div>
);
};

export default App;

With Jotai, managing state becomes straightforward and modular. Each piece of state is encapsulated in its own atom, making the state management granular and easy to reason about.

Hooks to remember:

  • atom — function that creates a new atom (a piece of state).
  • useAtom — a hook that provides access to both getter and setter methods for an atom.
  • useSetAtom — a hook that provides access to the setter method for an atom.
  • useAtomValue — a hook that provides access to the getter method for an atom.

Summary

Jotai offers a fresh and efficient approach to state management in React applications. Its simplicity, fine-grained state control, and seamless integration with React and TypeScript make it an excellent choice for developers. Whether you’re building a small project or a complex application, Jotai provides the tools to manage your state effectively, allowing you to focus on building cool features without the headache of complicated state management.

In a world where state management can often feel like a tangled mess, Jotai brings clarity and ease, making it not just a powerful tool, but a joy to use. Give Jotai a try, and you might find it becoming your go-to solution for state management in React.

If you enjoyed my article, don’t forget to leave a few claps 👏🏻 and follow me to stay updated with the articles I publish 🙂

More about Jotai: https://jotai.org

Image by rawpixel.com on Freepik

--

--

Maciej Poppek

A Senior? Front-end Developer working on a daily basis with JS, TS, React, and some other cool tech 🙂 https://www.linkedin.com/in/maciej-poppek/