Mastering State Management in React with Jotai

  • State management in React offers diverse library options.
  • Jotai is a new library based on atoms for state management.
  • Atoms create a dependency graph for state updates.
  • Jotai can be used for global, semi-global, or local state.
  • ProviderComponent and UseAtomHook are essential in using Jotai with React.

State management has always been a hot topic in the React community. With a plethora of libraries and solutions available, developers can choose from primitive solutions like the UseStateHook or more advanced libraries like Redux, MoveX, XState, Zustand, and now Jotai. While having numerous options can be daunting, it enriches the ecosystem by fostering innovation and diversity in approaches.

Jotai is an exciting new entrant in the realm of state management solutions for React. It introduces a concept based on atoms, which are essentially pieces of state. This concept, while popularized by libraries like Recoil, is not entirely new. It involves forming a dependency graph of state pieces and propagating updates across them. For instance, if you have three atoms, A, B, and C, where A depends on B, and B depends on C, any update to C will trigger updates to both B and A.

Unlike observables, atoms in Jotai do not hold values. They are merely definitions, with the actual values existing elsewhere. This separation allows developers to use atoms for global, semi-global, or local state management. By thinking of atoms as functions, much like React components, it becomes easier to grasp their utility in managing state.

Atoms in Jotai are defined using functions. For example, you can have a textAtom with an initial value of "HELLO", a textLengthAtom that calculates the length of textAtom, and an uppercaseAtom that converts textAtom to uppercase. These atoms are interconnected, so any change in textAtom will automatically update the others. This is achieved using the useAtom hook, which functions similarly to the useState hook, providing a value and an update function that triggers re-renders upon changes.

A key feature of Jotai is its ability to be used for global state management, although it's not truly global. Atoms can be used for semi-global or local states, which may initially seem counterintuitive. However, by viewing atoms as functions, their flexibility in state management becomes evident.

In React, dependencies in components are typically defined using props, states, or context. Jotai introduces a similar pattern with atoms. For example, a countAtom can be defined, and a doubleAtom can depend on it. When the countAtom changes, the doubleAtom is re-evaluated. The use of the get function, which retrieves atom values, is akin to the useContext hook in React, but with additional flexibility in changing atom dependencies.

Jotai also supports write operations on atoms. By adding a write function to an atom, it becomes writable, enabling state updates. This write function takes three parameters: get, set, and new value, allowing complex state manipulations. Primitive atoms, which serve as data sources in the dependency graph, can be defined with initial values and used to form intricate state management patterns.

Although Jotai atoms are designed for React, they are framework agnostic. The atom function is a helper for creating config objects, but technically, developers can define atom objects without it. To integrate Jotai with React, two functions are crucial: the ProviderComponent and the useAtom hook. The ProviderComponent stores atom values within the component tree, while the useAtom hook retrieves and updates these values.

In some scenarios, the Provider component can be omitted, allowing for global state management. This feature is particularly useful when there's only one Provider in memory. However, in cases with multiple Providers, each can maintain separate atom values, demonstrating the flexibility of Jotai in managing state across different contexts.

Jotai's design also supports server-side scenarios where multiple requests require isolated state management. While updating atom values on the server is currently hypothetical, the separation of definition and values lays the groundwork for potential future developments.

Jotai's framework-agnostic nature even allows for experiments like Jotajsx, which replaces React and React-dom libraries while retaining the same syntax. This and other experimental libraries hosted under the JotaiLabs GitHub organization showcase the potential for further developments and integrations beyond React.

Jotai presents a fresh perspective on state management in React, emphasizing the use of atoms as function-like, framework-agnostic state definitions. Whether you're an existing Jotai user or new to the library, exploring its capabilities can offer valuable insights into efficient state management.

08 Oct, 2024

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Don't Solve Problems, Eliminate Them
React Advanced 2021React Advanced 2021
39 min
Don't Solve Problems, Eliminate Them
Top Content
Kent C. Dodds discusses the concept of problem elimination rather than just problem-solving. He introduces the idea of a problem tree and the importance of avoiding creating solutions prematurely. Kent uses examples like Tesla's electric engine and Remix framework to illustrate the benefits of problem elimination. He emphasizes the value of trade-offs and taking the easier path, as well as the need to constantly re-evaluate and change approaches to eliminate problems.
Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
State management is not limited to complex applications and transitioning to a store offers significant benefits. Pinia is a centralized state management solution compatible with Vue 2 and Vue 3, providing advanced devtools support and extensibility with plugins. The core API of Pinia is similar to Vuex, but with a less verbose version of stores and powerful plugins. Pinia allows for easy state inspection, error handling, and testing. It is recommended to create one file per store for better organization and Pinia offers a more efficient performance compared to V-rex.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced 2023React Advanced 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
Using useEffect Effectively
React Advanced 2022React Advanced 2022
30 min
Using useEffect Effectively
Top Content
Today's Talk explores the use of the useEffect hook in React development, covering topics such as fetching data, handling race conditions and cleanup, and optimizing performance. It also discusses the correct use of useEffect in React 18, the distinction between Activity Effects and Action Effects, and the potential misuse of useEffect. The Talk highlights the benefits of using useQuery or SWR for data fetching, the problems with using useEffect for initializing global singletons, and the use of state machines for handling effects. The speaker also recommends exploring the beta React docs and using tools like the stately.ai editor for visualizing state machines.
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Watch video: Speeding Up Your React App With Less JavaScript
Mishko, the creator of Angular and AngularJS, discusses the challenges of website performance and JavaScript hydration. He explains the differences between client-side and server-side rendering and introduces Quik as a solution for efficient component hydration. Mishko demonstrates examples of state management and intercommunication using Quik. He highlights the performance benefits of using Quik with React and emphasizes the importance of reducing JavaScript size for better performance. Finally, he mentions the use of QUIC in both MPA and SPA applications for improved startup performance.
React Query: It’s Time to Break up with your "Global State”!
React Summit Remote Edition 2020React Summit Remote Edition 2020
30 min
React Query: It’s Time to Break up with your "Global State”!
Top Content
Global state management and the challenges of placing server state in global state are discussed. React Query is introduced as a solution for handling asynchronous server state. The Talk demonstrates the process of extracting logic into custom hooks and fixing issues with state and fetching logic. Optimistic updates with mutation are showcased, along with the benefits of using React Query for data fetching and mutations. The future of global state management is discussed, along with user feedback on React Query. The Talk concludes with an invitation to explore React Query for server state management.

Workshops on related topic

React, TypeScript, and TDD
React Advanced 2021React Advanced 2021
174 min
React, TypeScript, and TDD
Top Content
Featured Workshop
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Web3 Workshop - Building Your First Dapp
React Advanced 2021React Advanced 2021
145 min
Web3 Workshop - Building Your First Dapp
Top Content
Featured Workshop
Nader Dabit
Nader Dabit
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
Rethinking Server State with React Query
React Summit 2020React Summit 2020
96 min
Rethinking Server State with React Query
Top Content
Featured Workshop
Tanner Linsley
Tanner Linsley
The distinction between server state and client state in our applications might be a new concept for some, but it is very important to understand when delivering a top-notch user experience. Server state comes with unique problems that often sneak into our applications surprise like:
- Sharing Data across apps- Caching & Persistence- Deduping Requests- Background Updates- Managing “Stale” Data- Pagination & Incremental fetching- Memory & Garbage Collection- Optimistic Updates
Traditional “Global State” managers pretend these challenges don’t exist and this ultimately results in developers building their own on-the-fly attempts to mitigate them.
In this workshop, we will build an application that exposes these issues, allows us to understand them better, and finally turn them from challenges into features using a library designed for managing server-state called React Query.
By the end of the workshop, you will have a better understanding of server state, client state, syncing asynchronous data (mouthful, I know), and React Query.
Remix Fundamentals
React Summit 2022React Summit 2022
136 min
Remix Fundamentals
Top Content
Workshop
Kent C. Dodds
Kent C. Dodds
Building modern web applications is riddled with complexity And that's only if you bother to deal with the problems
Tired of wiring up onSubmit to backend APIs and making sure your client-side cache stays up-to-date? Wouldn't it be cool to be able to use the global nature of CSS to your benefit, rather than find tools or conventions to avoid or work around it? And how would you like nested layouts with intelligent and performance optimized data management that just works™?
Remix solves some of these problems, and completely eliminates the rest. You don't even have to think about server cache management or global CSS namespace clashes. It's not that Remix has APIs to avoid these problems, they simply don't exist when you're using Remix. Oh, and you don't need that huge complex graphql client when you're using Remix. They've got you covered. Ready to build faster apps faster?
At the end of this workshop, you'll know how to:- Create Remix Routes- Style Remix applications- Load data in Remix loaders- Mutate data with forms and actions
Vue3: Modern Frontend App Development
Vue.js London Live 2021Vue.js London Live 2021
169 min
Vue3: Modern Frontend App Development
Top Content
Workshop
Mikhail Kuznetsov
Mikhail Kuznetsov
The Vue3 has been released in mid-2020. Besides many improvements and optimizations, the main feature of Vue3 brings is the Composition API – a new way to write and reuse reactive code. Let's learn more about how to use Composition API efficiently.

Besides core Vue3 features we'll explain examples of how to use popular libraries with Vue3.

Table of contents:
- Introduction to Vue3
- Composition API
- Core libraries
- Vue3 ecosystem

Prerequisites:
IDE of choice (Inellij or VSC) installed
Nodejs + NPM
Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
JSNation 2023JSNation 2023
174 min
Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
Top Content
WorkshopFree
Alba Silvente Fuentes
Roberto Butti
2 authors
This SvelteKit workshop explores the integration of 3rd party services, such as Storyblok, in a SvelteKit project. Participants will learn how to create a SvelteKit project, leverage Svelte components, and connect to external APIs. The workshop covers important concepts including SSR, CSR, static site generation, and deploying the application using adapters. By the end of the workshop, attendees will have a solid understanding of building SvelteKit applications with API integrations and be prepared for deployment.