Jotai 使用

108 阅读1分钟

一、create atoms 创建

(1)Primitive atoms

import { atom } from 'jotai'

const countAtom = atom(0)

const countryAtom = atom('Japan')

const citiesAtom = atom(['Tokyo', 'Kyoto', 'Osaka'])

(2)Derived atoms, 又叫computed atoms。

const progressAtom = atom((get) => {
  const anime = get(animeAtom)
  return anime.filter((item) => item.watched).length / anime.length
})

另外,还可以自定义Derived atoms的写函数。

import { atom } from 'jotai'

const priceAtom = atom(10)

const readOnlyAtom = atom((get) => get(priceAtom) * 2)
const readWriteAtom = atom(
  (get) => get(priceAtom) * 2,
  (get, set, newPrice) => {
    set(priceAtom, newPrice / 2)
    set(, )
    // you can set as many atoms as you want at the same time
  },
)

二、use atoms 使用

useAtom hook,可以使用可读、可写

import { useAtom } from 'jotai'

const AnimeApp = () => {
  const [anime, setAnime] = useAtom(animeAtom)

  return (
    <>
      <ul>
        {anime.map((item) => (
          <li key={item.title}>{item.title}</li>
        ))}
      </ul>
      <button onClick={() => {
        setAnime((anime) => [
          ...anime,
          {
            title: 'Cowboy Bebop',
            year: 1998,
            watched: false
          }
        ])
      }}>
        Add Cowboy Bebop
      </button>
    <>
  )
}

usetAtomValue只读、useSetAtom只写。

指定使用只读范围,可以提升代码阅读和规范。

指定使用只写,可以提升组件性能。

This is especially useful when the performance is a concern, as the const [, setValue] = useAtom(valueAtom) will cause unnecessary rerenders on each valueAtom update.

import { useAtomValue, useSetAtom } from 'jotai'
const AnimeList = () => {
  const anime = useAtomValue(animeAtom)

  return (
    <ul>
      {anime.map((item) => (
        <li key={item.title}>{item.title}</li>
      ))}
    </ul>
  )
}

const AddAnime = () => {
  const setAnime = useSetAtom(animeAtom)

  return (
    <button onClick={() => {
      setAnime((anime) => [
        ...anime,
        {
          title: 'Cowboy Bebop',
          year: 1998,
          watched: false
        }
      ])
    }}>
      Add Cowboy Bebop
    </button>
  )
}

另外还可以像React原生一样,使用Provider的方式,使用数据。

注意:server side rendering的时候,一定需要提供一个顶层的Provider

三、utilities 工具

Storage: 数据持久化到 localStorage等jotai.org/docs/utilit…

zustand也支持

四、extensions 扩展

Immer 实现深层嵌套的数据更新问题。

zustand也支持

五、其他

与zustand的对比:docs.pmnd.rs/zustand/get…

(1)Firstly, Zustand is a single store, while Jotai consists of primitive atoms that can be composed together.

(2)Secondly, a Zustand store is an external store, making it more suitable when access outside of React is required.