0% found this document useful (0 votes)
137 views6 pages

Jotai Atoms: Read, Write, and Split

The document provides an overview of Jotai, a state management library for React, detailing its core concepts such as atoms, useAtom, Provider, and Store. It explains the different types of derived atoms (read-only, write-only, read-write) and how to utilize them, along with the use of async atoms and the immerAtom for managing deeply nested objects. Additionally, it covers utilities like splitAtom for handling arrays and various syntax tips for managing values in JavaScript.

Uploaded by

Đặng Tú
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views6 pages

Jotai Atoms: Read, Write, and Split

The document provides an overview of Jotai, a state management library for React, detailing its core concepts such as atoms, useAtom, Provider, and Store. It explains the different types of derived atoms (read-only, write-only, read-write) and how to utilize them, along with the use of async atoms and the immerAtom for managing deeply nested objects. Additionally, it covers utilities like splitAtom for handling arrays and various syntax tips for managing values in JavaScript.

Uploaded by

Đặng Tú
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SWC ( speedy web compiler) : Rust compile code

[Link]
[Link]
Core:
 atom
 useAtom
 Provider
 Store
You can also create derived atoms. We have three patterns:

 Read-only atom
 Write-only atom
 Read-Write atom
 get in the read function is to read the atom value. It's reactive and read
dependencies are tracked.
 set in the write function is to write atom value. It will invoke the write
function of the target atom.

Read only
Write derived
Write only derived atom
 initialValue: the initial value that the atom will return until its value is
changed.
 read: a function that's called on every re-render. The signature
of read is (get) => Value | Promise<Value>, and get is a function that
takes an atom config and returns its value stored in Provider as
described below. Dependency is tracked, so if get is used for an atom at
least once, the read will be reevaluated whenever the atom value is
changed.
 write: a function mostly used for mutating atom's values, for a better
description; it gets called whenever we call the second value of the
returned pair of useAtom, the useAtom()[1]. The default value of this
function in the primitive atom will change the value of that atom. The
signature of write is (get, set, update) => void | Promise<void>. get is
similar to the one described above, but it doesn't track the
dependency. set is a function that takes an atom config and a new value
which then updates the atom value in Provider. update is an arbitrary value
that we receive from the updating function returned by useAtom described
below.

const primitiveAtom = atom(initialValue)


const derivedAtomWithRead = atom(read)
const derivedAtomWithReadWrite = atom(read, write)
const derivedAtomWithWriteOnly = atom(null, write)

useAtom
The useAtom hook is to read an atom value in the state. The state can be seen
as a WeakMap of atom configs and atom values.
The useAtom hook returns the atom value and an update function as a tuple, just
like React's useState. It takes an atom config created with atom().
Initially, there is no value associated with the atom. Only once the atom is used
via useAtom, does the initial value get stored in the state. If the atom is a derived
atom, the read function is called to compute the initial value. When an atom is no
longer used, meaning all the components using it are unmounted, and the atom
config no longer exists, the value in the state is garbage collected.
const [value, setValue] = useAtom(anAtom)

In case you need to update a value of an atom without reading it, you can
use useSetAtom().
This is especially useful when the performance is a concern, as the const [,
setValue] = useAtom(valueAtom) will cause unnecessary rerenders on
each valueAtom update.

Provider
The Provider component is to provide state for a component sub tree. Multiple
Providers can be used for multiple subtrees, and they can even be nested. This
works just like React Context.
useStore
const Component = () => {
const store = useStore()
// ...
}

atom (Async)
Name
Jotai means "state" in Japanese. Zustand means "state" in German.

Analogy
Jotai is like Recoil. Zustand is like Redux.
Atom in atom
Async Read Atoms
Using async atoms, you gain access to real-world data while still
managing them directly from your atoms and with incredible ease.
We separate async atoms in two main categories: •Async read atoms
•Async write atoms
But there is a more jotai way of doing this with the loadable api present in
jotai/utils. By simply wrapping the atom in loadable util and it returns the value
with one of the three states: loadable, hasData and hasError.

Update deeply nested obj ( atom: nhu kieu context), dung immerAtom
import { useAtom } from 'jotai';
import { atomWithImmer } from 'jotai-immer';

const todo = {
todo: {
person: {
name: "David",
title: {
goal: "old todo"
},
}
}
};
const immerAtom = atomWithImmer(todo);

export default function Page() {


const [todoAtom, setAtomTodo] = useAtom(immerAtom);
const updateTodo = () => {
setAtomTodo(state => {
[Link] = "new title";
return state;
});
}
return (
<div className="app">
<h3>Name: {[Link]}</h3>
<p>Todo: {[Link]}</p>
<button onClick={updateTodo}>Update Todo</button>
</div>
)
}

splitAtom
 to split array element for each item working with array
 The splitAtom utility is useful for when you want to get an atom for each
element in a list. It works for read/write atoms that contain a list. When
used on such an atom, it returns an atom which itself contains a list of
atoms, each corresponding to the respective item in the original list
 Additionally, the atom returned by splitAtom contains a dispatch function in
the write direction (since v1.6.4), this is useful for when you want a simple
way to modify the original atom with actions such as remove, insert, and
move.
const todosAtom = atom(initialState)
const todoAtomsAtom = splitAtom(todosAtom)
each will have their own atom , atom will update on every render
const TodoList = () => {
const [todoAtoms, dispatch] = useAtom(todoAtomsAtom)
return (
<ul>
{[Link]((todoAtom) => (
<TodoItem
todoAtom={todoAtom}
remove={() => dispatch({ type: 'remove', atom: todoAtom })}
/>
))}
</ul>
)
}

?? syntax ( assign value to null or undefined value)


const x = null;
const y = 42;
const result1 = x ?? "Default"; // Since x is null, result1 will be "Default"
const result2 = y ?? "Fallback"; // Since y is not null, result2 will be 42

? syntax
a?.b value : it return undefine to prevent value is null or undefined

!! syntax
take the boolean value of this variable
If a is falsy, then !a is true, and !!a will be false.
If a is truthy, then !a is false, and !!a will be true.

falsy (e.g., false, null, undefined, 0, NaN, or an empty string '')

Should use ? : instead of a && b ( co the a kp la boolean value tra ve 0,1)

Avoid React Context Trap


Place at the right context wrap common component

React query, tan-stack


Nomad : deploy

You might also like