Adding an array structure
An array structure is tricky to handle in React. When a component renders an array structure, we need to pass stable key
properties to the array items. This is especially necessary when we remove or reorder the array items.
In this section, we'll learn how to handle array structures in Jotai. We'll start with a traditional approach, and then a new pattern that we call Atoms-in-Atom.
Let's use the same to-do app example that we used in the Handling structured data section of Chapter 7, Use Case Scenario 1 – Zustand.
First, we define a Todo
type. It has the id
string, title
string, and done
Boolean properties, as illustrated in the following code snippet:
type Todo = { id: string; title: string; done: boolean; };
Next, we define todosAtom
, which represents an array of defined Todo
items, as follows:
const todosAtom = atom<Todo[]>([]);
We annotate the atom()
function with the...