Prevent Rerenders and Add Functionality with Jotai Write-only Atoms

Daishi Kato
InstructorDaishi Kato

Share this video with your friends

Send Tweet
Published a year ago
Updated 5 months ago

We have a naive SVG app that can draw dots onto a canvas as the mouse scrolls over. You’ll notice as you drag the mouse around the canvas that the commit count in the top left corner increases. This is because the SVG component rerenders on every dot that’s drawn.

The rerenders are due to the fact that we are using the dotsAtom directly in the component. This is where write-only atoms come in handy. They can receive a write function that will handle the updates to your atom state which will fix the rerender issue.

We will also cover how to compose write-only atoms to add functionality.

Instructor: [0:00] What we have now is a native SVG app. We can draw a dot only by moving mouse. On top left, there's a number showing a commit count indicating how many times the canvas component re-renders.

[0:14] Currently, the number increases as we draw more dots. It's due to the fact that we use dotAtom directly in the component. This is extra re-renders which we want to avoid sometimes.

[0:27] To fix it, let's define a new write-only atom. Usually, we put, no, for the first argument and the second argument is, write function. The write function takes three arguments, get function, set function, and update.

[0:43] The update is something we get from the invocation of the updating atom. In this case, we receive a point and add it to the dotAtom using the set function. With this new atom in the component, it doesn't re-render even if dotAtom changes. We confirm the commit count doesn't increase when drawing.

[1:05] Now, let's define a new booleanAtom called drawingAtom. Also, define two write-only atoms to enable and disable drawing. With this booleanAtom, we only add dots while drawing. We use the get function to get the atom value.

[1:23] Using the two new write-only atoms in the component, we toggle the drawingAtom on mouse down and the mouse up. Now, we can draw dots only when we are dragging mouse on the canvas. Write-only atoms are powerful and you can organize updating logic outside components.