How to manage state in React using Jotai
State management on small-scale projects is often as simple as using React hooks and properties. However, as the application grows and needs to share data access between the generating components, it often leads to prop drilling. Unfortunately, prop drilling can quickly clutter up the codebase and present scalable challenges.
While Redux provides a state management solution, its API can be overwhelming for relatively small projects. In contrast, Jotai is a simple state management library that leverages independent state units called atoms for state management, removing challenges like prop drilling and allowing a simpler, and more extensible, state management approach.
What is Jotai and how does it work?
Jotai is a state management library that provides a simpler solution than complex alternatives like Redux. It uses independent units of state named atom to manage state in React applications.
Best of all, the various components in this application, access and update those atoms using the Jotai-provided hook called useAtom . Here is an example sample of how to create a Jotai atom:
import { atom } from 'jotai'; const countAtom = atom(1);
To access and work with atoms in Jotai, you can use the useAtom hook , which, like any other React hook, allows you to access and update the value of state in the function component.
Here is an example demonstrating its usage:
import { useAtom } from 'jotai'; const countAtom = atom(1); function MyComponent() { const [count, setCount] = useAtom(countAtom); const increment = () => setCount((prevCount) => prevCount + 1); return (
Count: {count}
Increment ); }
In this example, the useAtom hook is used to access the atom countAtom and its associated value. The setCount function is used to update the value of the atom and any associated components will automatically re-render with the updated value.
By enabling only affected components, it reduces unnecessary re-renders on the app. This targeted approach to re-rendering enhances the overall performance of the application.
Once you've covered the basics, let's start building a To-do React app to better understand Jotai's state management capabilities.
Managing State in React Using Jotai
To get started, create a React app. Alternatively, you can use Vite to set up a React project. When scaffolding a basic React app, go ahead and install Jotai in your app.
npm install jotai
Next, to use Jotai in your app, you need to include the entire app with a Provider component . This component contains a place that acts as the central component, dedicated to providing atom values for the entire application.
In addition, it allows you to declare the initial atom state. By attaching your app to a Provider, all components in the application have access to the atom you defined, and they can then interact and update state via the useAtom hook .
import { Provider } from "jotai";
Now include the app in index.js or main.jsx like below:
import React from 'react' import ReactDOM from 'react-dom/client' import App from './App.jsx' import './index.css' import { Provider } from "jotai"; ReactDOM.createRoot(document.getElementById('root')).render( , )
Configure Data Store
Store acts as a central repository for the state of the application. It usually contains the definition of the atom, selector, and any other related functions needed for state management by Jotai.
In this case, it manages the atoms to manage the item list for the To-do application. In the src folder , create TodoStore.jsx and add the code below:
import { atom } from "jotai"; export const TodosAtom = atom([]);
By creating and exporting TodosAtom, you can freely interact and update the todo status across different components of your application.
To-Do Application Function Deployment
Now that you have Jotai configured in your React app and have created an atom to manage the state of the application, go ahead and create a simple to-do component to perform add, remove, and edit functions for the items to be handled.
Create a new components/Todo.jsx file in the src folder . In this file, add the code below:
1. Import datastore and useAtom hook :
import React, { useState } from 'react'; import { TodosAtom } from './TodoStore'; import { useAtom } from 'jotai';
2. Create functional components and add JSX elements.
const Todo = () => { return ( setValue(event.target.value)} /> Add Todo
{todos.map(todo => (
- {todo.text}
))}
); }; export default Todo;
This component presents a simple user interface for managing to-do lists.
3. Finally, implement the add and remove todo function.
const [value, setValue] = useState(''); const [todos, setTodos] = useAtom(TodosAtom); const handleAdd = () => { if (value.trim() !== '') { setTodos(prevTodos => [ .prevTodos, { id: Date.now(), text: value }, ]); setValue(''); } }; const handleDelete = id => { setTodos(prevTodos => prevTodos.filter(todo => todo.id !== id)); };
- The handeAdd function is responsible for adding the item to be refreshed in the list.
- setTodos is then called to update the todo list in the atom by adding that new item.
- handleDelete is responsible for removing the todo item from the list.
Above is how to use Jotai to manage state in React app. Hope the article is useful to you.
You should read it
- How to build a CRUD to-do list app and manage its state in React
- Best React Usages in 2023
- How to manage date and time in React using Moment.js
- How to speed up React apps with code splitting
- How to use Sass in React
- Tooltip creation tools are useful with ReactJS
- React mistakes to avoid for successful app development
- How to develop React apps that analyze emotions using OpenAI API
May be interested
- How to develop React apps that analyze emotions using OpenAI APIwith openai's api tool, you can analyze, generate detailed overview reports, and easily come up with solutions to increase leads. here's how to create a react app that analyzes market sentiment using open ai's api.
- How to create a swipeable interface in a React app using Swiperswiper is a flexible library that allows you to create swipeable interfaces in react applications. let's explore how to create a swipeable interface in a react app using swiper!
- Pi goes public and then plummets: Pi players reactexcept for the 'pi players' who spend time and effort collecting free pi, the buyers and sellers are in a rather uncertain state.
- Instructions for creating a Tic-Tac-Toe game using React-Nativelearning how to develop a tictactoe game allows you to learn basic styling, user interaction, and more. all will help you improve the basic foundation in react-native.
- How to save React form data in Mongo Databasetry adding mongodb to your web stack to see how easy it is to store and query form data!
- Windows User State Virtualization - Part 3: Virtualizing application statein the third part of this series, we will show you how to manage the appdataroaming folder when virtualizing application settings and data.
- How to build a QR Code generator using Reactthis utility app allows you to create your own qr code. you can build it easily, using the powerful qrcode library.
- Compare useEffect, useLayoutEffect and useEffectEvent in Reactin this article, let's explore react's data fetching hooks - useeffect, uselayouteffect, and useeffectevent - comparing their functionalities for efficient application deployment.
- How to improve search in React using Debouncingdebouncing will help you avoid overloading the server and optimize application performance. below are detailed instructions.
- How to Fix 'Printer in Error State' on Windowsthe printer in error state message on windows can appear for many reasons, such as a failed connection, driver issue, or misconfiguration of system services.