Introduction to Jotai. Part 1

Photo by 은 하 on Unsplash

Introduction to Jotai. Part 1

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)} />
}

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)} />
}

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)

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>
}

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>

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.