Structure Jotai Atoms and Add Functionality to a React App

Daishi Kato
InstructorDaishi Kato

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

Right now, the app that we have built draws dots on SVG on canvas. As you start applications you'll often find working in one file works the best to build something quickly. There comes a point when you need to move code out of the single file and structure it.

First, we'll see how the app has been refactored into 3 files. We are able to export the atoms and components that are needed throughout our app while keeping internal logic isolated in the file meaning not all atoms are exported.

Next, we'll create a new atom that takes a set of points and generates a path. You'll see how to create new functionality through an atom and import it into another component that's using Jotai atoms.

Instructor: [0:00] We are building an app based on SVG. For now, we can draw dots on canvas. We used to have all code in a single App.tsx file, but now we structure it a little bit. We have three files now. App.tsx, SvgRoot.tsx, and SvgDot.tsx.

[0:21] There are several approaches to structure atoms and components. For this time, we put atom definitions in a correlated component file. This allows us to only export atoms that are used by other components. All remaining atoms are not exported.

[0:41] Now, let's add a new feature committing dots and drawing a path. A new file named SvgShape.tsx will be responsible to it. We define shapeAtom to hold a path.

[0:54] Another atom as a shapeAtom is to receive dots and set it as a path. We use naive points to parse function this time. If you change this function, it can create a nicer path. SvgShape component uses the shapeAtom and draws a path.

[1:13] In SvgDot.tsx, we add a new atom to commit dots. It has a new shape and clear dots. Finally, in the SvgRoot component, we commit dots on MouseUp. We also add SvgShape component along with SvgDot component. In the end, our app works for drawing one path.