Derive State from a Jotai Atom in React

Daishi Kato
InstructorDaishi Kato

Share this video with your friends

Send Tweet
Published a year ago
Updated 11 months ago

Derived atoms can be created from other atoms. To do so, you pass a read function as the first argument which is traditionally called get. this will allow you to retrieve any other atom and transform the data received.

The derived atom can be used just like a normal atom but this way lets you easily separate logic outside of a component.

Daishi Kato: [0:00] Right now, this is an empty app with SVG. We would like to add a tiny drawing feature. Let me define an atom called dotsAtom which holds a list of points. In the SvgDots component, we use the dotsAtom and draw small circles. In the SvgRoot component, we define onMouseMove handler to add a point to the dotsAtom.

[0:26] This component only uses the second part of what useAtom returns. See, we can draw dots by moving a mouse on the canvas. Suppose we want to show the number of dots. In the Stats component, we add a new list item to show the number using the same dotsAtom and we get its length. If we draw more dots, the number increases.

[0:52] Instead of using dotsAtom in the Stats component, we define a new derived atom. A derived atom can be created from other atoms. To define it, we parse a function that returns the atom value.

[1:06] The argument of the function is usually called get. Get is a function that returns a value of any atom. We can use a derived atom just like a normal atom. The stats component can be written with the numberOfDotsAtom, and it works. This example may seem trivial, but the idea is to separate logic outside the components.

[1:30] To recap, at first, we define atoms here. This can be done in a different file. We then use the defined atoms in components.