DEV Community

Cover image for Introduction to Jotai. From React hooks to Jotai atoms
Andrzej Fricze
Andrzej Fricze

Posted on

Introduction to Jotai. From React hooks to Jotai atoms

Jotai is simple. There's one concept there: atom. You eat with it, you sleep with it, you fight with it.

You create an atom with atom function. You can use atom in your component just like React local state. Instead of useState, write useAtom.

const textAtom = atom('hello')

const Input = () => {
  const [text, setText] = useAtom(textAtom)
  return <input value={text} onChange={(e) => setText(e.target.value)} />
}
Enter fullscreen mode Exit fullscreen mode

This component works the same way as similar component with useState.

const Input = () => {
  const [text, setText] = useState('hello')
  return <input value={text} onChange={(e) => setText(e.target.value)} />
}
Enter fullscreen mode Exit fullscreen mode

Atoms are more flexible than the local state. They live outside components. Components refer to atoms but don't own them. Atoms can be composed together. Using composition you can create derived atoms. Derived atom holds data dependent on other atoms. When value of the source atom changes, value of the derived atom also changes.

const textLengthAtom = atom((get) => get(textAtom).length)
Enter fullscreen mode Exit fullscreen mode

Atom above is a derived atom. Its value is length of text from textAtom. You can use it in any component you want.

const TextLength = () => {
  const [length] = useAtom(textLengthAtom)
  return <div>Length: {length}</div>
}
Enter fullscreen mode Exit fullscreen mode

Input and TextLength components are not connected. Their state comes from atoms that live outside them. You can use them in your application in any place you want. State will be propagated properly.

<Provider>
  <Container>
    <Input />
  </Container>
  <Container>
    <Column>
      <TextLength />
    </Column>
  </Container>
</Provider>
Enter fullscreen mode Exit fullscreen mode

If you build React application with hooks, go on and try replacing your useState with useAtom from Jotai. You install Jotai with npm i jotai. It comes with TypeScript declarations. No need to look for additional typings.

Shown code is based on Jotai official examples. Check out this code live.

Check out Jotai website for docs and more examples of Jotai code.

Check out next part of Introduction to Jotai.

Top comments (0)