jotai
v2.11.0


jotai.org 또는 npm i jotai 방문하십시오
JOTAI는 간단한 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 사용하면 모든 원자의 상황에 맞는 값을 가져올 수 있습니다.
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 )
. . . 두 번째 인수에서 쓰기 기능을 지정하십시오. 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에 대해 자세히 알아보십시오.