Read Only atoms

Readonly atoms are use to read the value of the other atoms. You can't set or change their value directly because these atoms rely on their parent atoms.

const textAtom = atom('readonly'); const uppercase = atom((get) => get(textAtom).toUpperCase());

These atoms takes a callback with a paramater get which allows us to read other atoms value. Changing the value of parent will also updated the derived atom.

const firstName = atom('John'); const lastName = atom('Harris'); const fullName = atom((get) => get(firstName) + " " + get(lastName));

You can do more than just simply read the value of other atoms like filter and sorted out them or map over the values of the parent atom. And this is the beauty of it, Jotai gracefully lets you create dumb atoms derivated from even more dumb atoms. Here is a example of getting the list of all online and offline friends.

const friendsStatus = atom([ { name: "John", online: true }, { name: "David", online: false }, { name: "Micheal", online: true } ]); const onlineFriends = atom((get) => get(friendsStatus).filter((item) => item.online)); const offlineFriends = atom((get) => get(friendsStatus).filter((item) => !item.online));
import { atom, useAtom } from 'jotai';

const textAtom = atom('readonly atoms')
const uppercase = atom((get) => get(textAtom).toUpperCase())

export default function Page() {
  const [lowecaseText, setLowercaseText] = useAtom(textAtom);
  const [uppercaseText] = useAtom(uppercase);
  const handleClick = (e) => setLowercaseText(e.target.value);
  return (
    <div className="app">
      <input value={lowecaseText} onChange={handleClick} />
      <h1>{uppercaseText}</h1>
    </div>
  )
}
Open on CodeSandbox