Atoms
Atoms contain the source of truth for our application state. In our todo-list, the source of truth will be an array of objects, with each object representing a todo item.
We'll call our list atom todoListAtom
and create it using the atom()
function:
We give our atom a unique path
and set the defaultValue
to an empty array. To read the contents of this atom, we can use the useStateXValue()
hook in our TodoList
component:
The commented-out components will be implemented in the sections that follow.
To create new todo items, we need to access a setter function that will update
the contents of the todoListAtom
. We can use the useStateXValueSetter()
hook to get a setter function in our TodoItemCreator
component:
Notice we use the updater form of the setter function so that we can create a new todo list based on the old todo list.
The TodoItem
component will display the value of the todo item while allowing you to change its text and delete the item. We use useStateX()
to read todoListAtom
and to get a setter function that we use to update the item text, mark it as completed, and delete it. Note the use of placehoder in the path for index (":index") which is dynamically set to the id of the todo item on component initialization.
And with that we've got a fully functional todo list! In the next section we'll see how we can use selectors to take our list to the next level.