惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyberwarzone
Cyberwarzone
Recorded Future
Recorded Future
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
博客园 - Franky
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
SecWiki News
SecWiki News
V
V2EX
S
Secure Thoughts
GbyAI
GbyAI
F
Full Disclosure
云风的 BLOG
云风的 BLOG
Security Archives - TechRepublic
Security Archives - TechRepublic
Cloudbric
Cloudbric
美团技术团队
H
Hacker News: Front Page
Latest news
Latest news
Y
Y Combinator Blog
C
Cybersecurity and Infrastructure Security Agency CISA
B
Blog RSS Feed
雷峰网
雷峰网
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Apple Machine Learning Research
Apple Machine Learning Research
Engineering at Meta
Engineering at Meta
AI
AI
The Hacker News
The Hacker News
Recent Announcements
Recent Announcements
S
Security @ Cisco Blogs
Blog — PlanetScale
Blog — PlanetScale
The Last Watchdog
The Last Watchdog
T
The Blog of Author Tim Ferriss
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园_首页
J
Java Code Geeks
Attack and Defense Labs
Attack and Defense Labs
V
Vulnerabilities – Threatpost
A
About on SuperTechFans
P
Palo Alto Networks Blog
P
Privacy International News Feed
V2EX - 技术
V2EX - 技术
C
Cisco Blogs
I
Intezer
T
Troy Hunt's Blog
NISL@THU
NISL@THU
WordPress大学
WordPress大学
N
News and Events Feed by Topic
腾讯CDC

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
A Guide to Jotai: the Minimalist React State Management Library
Dmitri Pavlutin · 2021-03-30 · via Dmitri Pavlutin Blog

For a long time, Redux had been the leader library of global state management in React. But with the introduction of hooks, I have found that libraries like react-query or useSWR() handle the fetching of data with less boilerplate.

But the simple UI state like side-menu expand, theme, dark-mode, etc. require separate management — in which case a simple global state management library like Jotai (https://github.com/pmndrs/jotai) becomes handy.

In this post, you will learn how to use Jotai.

Table of Contents

  • 1. Search query: a global state variable
  • 2. Jotai atoms
    • 2.1 Search query atom
  • 3. Jotai derived atoms
  • 4. Conclusion

1. Search query: a global state variable

An application has a header and main content components. The header component has an input field where the user can introduce a search query. The main component should display the search query introduced in the input field.

Here's the initial sketch of the application:


import { useState } from 'react';

function App() {

return (

<div>

<Header />

<Main />

</div>

);

}

function Header() {

const [search, setSearch] = useState('');

const handleChange = event => setSearch(event.target.value);

return (

<header>

<input type="text" value={search} onChange={handleChange} />

</header>

);

}

function Main() {

// How to access the search?

return <main>Search query: ???</main>;

}


Open the demo.

<App> is composed of 2 components: <Header> and <Main>.

<Header> is a component that contains an input field where the user introduces a search query.

<Main> is the component that should render the query entered into the input field. How would you access the value here?

The search query is a global state variable. And Jotai library can help you here using a construction named atom.

2. Jotai atoms

A piece of state in Jotai is represented by an atom. An atom accepts an initial value, be it a primitive type like a number, string, or more complex structures like arrays and objects.


import { atom } from 'jotai';

const counterAtom = atom(0);


counterAtom is the atom that holds the counter state.

But the atom alone doesn't help much. To read and update the atom's state Jotai provides a special hook useAtom():


import { atom, useAtom } from 'jotai';

export const counterAtom = atom(0);

export function CounterButton() {

const [count, setCount] = useAtom(counterAtom);

const handleClick = () => {

setCount(number => number + 1); // Increment number

};

return (

<div>

{count}

<button onClick={handleClick}>Increment</button>

</div>

);

}


Open the demo.

const [count, setCount] = useAtom(counterAtom) returns a tuple where the first item is the value of the state, and the second is a state updater function.

count contains the atom's value, while setCount() can be used to update the atom's value.

The selling point of atoms is that you can access the same atom from multiple components. If a component updates the atom, then all the components that read this atom are updated. This is the global state management!

For example, let's read counterAtom value in an another component <CurrentCount>:


import { useAtom } from 'jotai';

import { counterAtom } from './Button';

function CurrentCount() {

const [count] = useAtom(counterAtom);

return <div>Current count: {count}</div>;

}


Open the demo.

When the value of counterAtom changes (due to counter increment), then both components <CounterButton> and <CurrentCount> are going to re-render.

Jotai atom

What's great about useAtom(atom) hook keeps the same API as the built-in useState() hook — which also returns a tuple of state value and an updater function.

2.1 Search query atom

Now let's return to the problem of section 1: how to share the search query from the <Header> component in <Main> component.

You might already see the solution: let's create an atom searchAtom and share it between <Header> and <Main> components:


import { useState } from 'react';

import { atom, useAtom } from 'jotai';

function App() {

return (

<div>

<Header />

<Main />

</div>

);

}

const searchAtom = atom('');

function Header() {

const [search, setSearch] = useAtom(searchAtom);

const handleChange = event => setSearch(event.target.value);

return (

<header>

<input type="text" value={search} onChange={handleChange} />

</header>

);

}

function Main() {

const [search] = useAtom(searchAtom);

return <main>Search query: "{search}"</main>;

}


Open the demo.

const searchAtom = atom('') creates the atom that's going to hold the search query global state variable.

Inside of the <Header> component const [search, setSearch] = useAtom(searchAtom) returns the current search value, as well as the updater function.

As soon as the user types into the input field, handleChange() event handler updates the atom value: setSearch(event.target.value).

<Main> component can also access the searchAtom value: const [search] = useAtom(searchAtom). And when the atom's value changes due to the user typing into the input, <Main> component is updated to receive the new value.

In conclusion, atoms are global state pieces that can be accessed and modified by any component.

3. Jotai derived atoms

If you find yourself calculating data from an atom's value, then you may find useful the derived atoms feature of Jotai.

You can create a derived atom when supplying a callback function to atom(get => get(myAtom)): in which case Jotai invokes the callback with a getter function get from where you can extract the value of the base atom get(myAtom).


import { atom } from 'jotai';

const numberAtom = atom(2);

const isEvenAtom = atom(get => get(numberAtom) % 2 === 0);


In the example above numberAtom holds a number. isEvenAtom is a derived atom that determines whether the number stored in numberAtom is even.

Derived Atom

Of course, as soon as the base atom changes, the derived atom changes too.

For example, let's create isNameEmptyAtom derived atom that determines the string stored in nameAtom is empty:


import { atom, useAtom } from 'jotai';

const nameAtom = atom('Batman');

const isNameEmptyAtom = atom(get => get(nameAtom).length === 0);

function HeroName() {

const [name, setName] = useAtom(nameAtom);

const [isNameEmpty] = useAtom(isNameEmptyAtom);

const handleChange = event => setName(event.target.value);

return (

<div>

<input type="text" value={name} onChange={handleChange} />

<div>Is name empty: {isNameEmpty ? 'Yes' : 'No'}</div>

</div>

);

}


Open the demo.

What's even better is that you can create a derived atom from multiple base atoms!


import { atom } from 'jotai';

const counterAtom1 = atom(0);

const counterAtom2 = atom(0);

const sumAtom = atom((get) => get(counterAtom1) + get(counterAtom2));


sumAtom is derived from 2 base atoms: counterAtom1 and counterAtom2.

Derived From Multiple Base Atoms

4. Conclusion

I like Jotai for its minimalistic but flexible way to manage a simple global state.

To create a global state variable you need 2 steps:

A) Define the atom for your global state variable:


const myAtom = atom(<initialValue>);


B) Then access the atom's value and updater function inside of the component using the special hook useAtom(<atom>):


function MyComponent() {

const [value, setValue] = useAtom(myAtom);

// ...

}


I found that Jotai fits well to manage simple global variables, as a complement to asynchronous state management libraries like react-query and useSWR().

The post has described the basic functionality of Jotai. Visit the repository https://github.com/pmndrs/jotai to read about all the features.

Would you use Jotai to manage simple global state variables? What features, in your opinion, this library is still missing?