Saturday, August 19, 2023

Calling write-only atoms in Jotai

Every atom in Jotai, when called through its useAtom primitive, returns a tuple of value + setter, just like React’s own useState. In a Jotai write-only atom, however, there is no value, so the canonical call is:

const [_, setVal] = useAtom(myValAtom);

In order to get rid of the verbose underscore, and thus the whole useless tuple, I wrote the following function:

import {WritableAtom} from 'jotai';

/**
 * Syntactic sugar to useAtom() for write-only atoms.
 */
export function useWriteAtom<V, A extends unknown[], R>(a: WritableAtom<V, A, R>) {
	const [_, setFunc] = useAtom(a);
	return setFunc;
}

The atom type was copied straight from Jotai’s TypeScript definitions, so the type inference works seamlessly. The example now can be written as:

const setVal = useWriteAtom(myValAtom);

No comments: