React State Management with Jotai
State management in React applications has always been a topic of great interest among developers. With a plethora of libraries available, choosing the right one can be overwhelming. One rising star in this space is Jotai, a minimalist state management library that allows you to manage state with a simple and intuitive API. In this blog post, we’ll explore Jotai: how it works, its core concepts, and how to implement it in your React applications.
What is Jotai?
Jotai is a state management library for React applications that provides a simple way to manage state using atomic state management principles. It is built on the idea of atoms, which represent pieces of state, allowing you to compose and manage state in a more granular way. Compared to larger state management libraries like Redux, Jotai is lightweight and less opinionated, making it a great choice for small to medium-sized applications.
Why Use Jotai?
There are several reasons developers might choose Jotai for state management in their React projects:
- Simplicity: Jotai’s API is straightforward, making it easy to understand and integrate into existing applications.
- Minimalist: Unlike many other libraries, Jotai does not impose a specific way of structuring your state management, giving developers the flexibility to adopt it as they see fit.
- Performance: Jotai uses React’s built-in features to minimize unnecessary re-renders, ensuring efficient updates to your UI.
- TypeScript Support: It is built with TypeScript in mind, offering an excellent developer experience for those using type checking in their applications.
Installation
Getting started with Jotai is easy. You can install it using npm or yarn. Open your terminal and run the following command:
npm install jotai
or
yarn add jotai
Core Concepts of Jotai
To effectively use Jotai, understanding its key concepts is crucial:
Atoms
Atoms are the primary building blocks of Jotai. They represent a piece of state in your application. Each atom can be read from and written to independently, allowing you to manage state in a modular way. Here’s an example of defining an atom:
import { atom } from 'jotai';
const countAtom = atom(0); // Initial state is 0
Using Atoms in Components
To use an atom in a component, you can utilize the useAtom hook. This hook returns the current state and a setter function to update that state:
import React from 'react';
import { useAtom } from 'jotai';
import { countAtom } from './atoms'; // Assume you exported the atom
const Counter = () => {
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>
);
};
Derived Atoms
Derived atoms allow you to create atoms that depend on other atoms. This is useful for keeping your state logic clean and efficient. You can derive state from existing atoms using the atom function:
const doubledCountAtom = atom((get) => get(countAtom) * 2);
This derived atom will always return double the value of countAtom. You can use it similarly in your components:
const DoubledCounter = () => {
const [doubledCount] = useAtom(doubledCountAtom);
return <h2>Doubled Count: {doubledCount}</h2>;
};
Example: Building a Todo List with Jotai
To illustrate how to use Jotai in a real-world application, let’s build a simple Todo list app.
Setting Up Atoms for Todos
First, we’ll create an atom for managing our todos:
const todosAtom = atom([]); // Initialize with an empty array
Creating the Todo List Component
Next, we’ll create a component to add and display todos:
const TodoList = () => {
const [todos, setTodos] = useAtom(todosAtom);
const [newTodo, setNewTodo] = React.useState('');
const addTodo = () => {
if (newTodo.trim()) {
setTodos([...todos, newTodo]);
setNewTodo('');
}
};
return (
<div>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
placeholder="Add a new todo..."
/>
<button onClick={addTodo}>Add Todo</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}</ul>
</div>
);
};
Render Your TodoList Component
Finally, render your TodoList component in your application:
import React from 'react';
import { Provider } from 'jotai';
import { TodoList } from './TodoList';
const App = () => (
<Provider>
<h1>My Todo List</h1>
<TodoList />
</Provider>
);
export default App;
The use of the Provider component from Jotai wraps your entire application, allowing all child components to access the atoms defined anywhere in your React tree.
Testing Jotai State Management
To ensure that your Jotai state management logic works as expected, you can use testing libraries like Jest in conjunction with React Testing Library. Here’s an example of how you might test the TodoList component:
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { Provider } from 'jotai';
import TodoList from './TodoList';
test('adds a new todo', () => {
render(
<Provider>
<TodoList />
</Provider>
);
fireEvent.change(screen.getByPlaceholderText(/add a new todo.../i), {
target: { value: 'Learn Jotai' },
});
fireEvent.click(screen.getByText(/add todo/i));
expect(screen.getByText(/learn jotai/i)).toBeInTheDocument();
});
This simple test checks that when you add a todo, it successfully shows up in the document.
Conclusion
Jotai provides a unique and powerful way to manage state in React applications. Its atomic approach enables developers to maintain clean and modular state management without the overhead of larger libraries. Whether you are building a small application or just looking for a lighter alternative to Redux, Jotai is definitely worth considering.
With its easy-to-understand API and excellent performance, you’re sure to have a positive experience using Jotai in your next React project. Explore its documentation and start building amazing applications today!
Further Reading
Get Started with Jotai
Now that you’re familiar with Jotai, go ahead and experiment with it in your projects! Share your experiences and any interesting state management strategies you come up with using Jotai.