jotai
v2.11.0


jotai.orgまたはnpm i jotaiにアクセスしてください
Jotaiは、Simple UseStateの交換からEnterprise TypeScriptアプリケーションに拡大します。
例:デモ1 |デモ2
原子は状態を表します。必要なのは、文字列や数字、オブジェクト、アレイなどのプリミティブ値である可能性がある初期値を指定することだけです。必要なだけ多くの原始原子を作成できます。
import { atom } from 'jotai'
const countAtom = atom ( 0 )
const countryAtom = atom ( 'Japan' )
const citiesAtom = atom ( [ 'Tokyo' , 'Kyoto' , 'Osaka' ] )
const mangaAtom = atom ( { 'Dragon Ball' : 1984 , 'One Piece' : 1997 , Naruto : 1999 } )React.useStateのように使用できます。
import { useAtom } from 'jotai'
function Counter ( ) {
const [ count , setCount ] = useAtom ( countAtom )
return (
< h1 >
{ count }
< button onClick = { ( ) => setCount ( ( c ) => c + 1 ) } > one up </ button >
...最初の引数として読み取り関数を渡すことにより、既存の原子から新しい読み取り専用原子を作成できます。 get使用すると、ATOMのコンテキスト値を取得できます。
const doubledCountAtom = atom ( ( get ) => get ( countAtom ) * 2 )
function DoubleCounter ( ) {
const [ doubledCount ] = useAtom ( doubledCountAtom )
return < h2 > { doubledCount } </ h2 >
}複数の原子を組み合わせて導出された原子を作成できます。
const count1 = atom ( 1 )
const count2 = atom ( 2 )
const count3 = atom ( 3 )
const sum = atom ( ( get ) => get ( count1 ) + get ( count2 ) + get ( count3 ) )または、FPパターンが好きな場合...
const atoms = [ count1 , count2 , count3 , ... otherAtoms ]
const sum = atom ( ( get ) => atoms . map ( get ) . reduce ( ( acc , count ) => acc + count ) )読み取り関数を非同期関数にすることもできます。
const urlAtom = atom ( 'https://json.host.com' )
const fetchUrlAtom = atom ( async ( get ) => {
const response = await fetch ( get ( urlAtom ) )
return await response . json ( )
} )
function Status ( ) {
// Re-renders the component after urlAtom is changed and the async function above concludes
const [ json ] = useAtom ( fetchUrlAtom )
. . .2番目の引数で書き込み関数を指定します。 get原子の現在の値を返します。 set原子の値を更新します。
const decrementCountAtom = atom (
( get ) => get ( countAtom ) ,
( get , set , _arg ) => set ( countAtom , get ( countAtom ) - 1 )
)
function Counter ( ) {
const [ count , decrement ] = useAtom ( decrementCountAtom )
return (
< h1 >
{ count }
< button onClick = { decrement } > Decrease </ button >
...読み取り関数を定義しないでください。
const multiplyCountAtom = atom ( null , ( get , set , by ) =>
set ( countAtom , get ( countAtom ) * by ) ,
)
function Controls ( ) {
const [ , multiply ] = useAtom ( multiplyCountAtom )
return < button onClick = { ( ) => multiply ( 3 ) } > triple </ button >
}準備ができたら、書き込み関数を非同期関数と呼び出しsetしてください。
const fetchCountAtom = atom (
( get ) => get ( countAtom ) ,
async ( _get , set , url ) => {
const response = await fetch ( url )
set ( countAtom , ( await response . json ( ) ) . count )
}
)
function Controls ( ) {
const [ count , compute ] = useAtom ( fetchCountAtom )
return (
< button onClick = { ( ) => compute ( 'http://count.host.com' ) } > compute </ button >
. . .Jotaiの流体インターフェースは偶然ではありません。原子は約束のようにモナドです!モナドは、変化に最適化されたモジュール式、純粋で、堅牢で理解可能なコードの確立されたパターンです。 JotaiとMonadsの詳細を読んでください。