- Published on
Jotai: State Management in React
- Authors
- Name
- Shelton Ma
Jotai
install package
pnpm install jotai
Create atoms
import { atom } from 'jotai' const countAtom = atom(0) const countryAtom = atom('Japan') const citiesAtom = atom(['Tokyo', 'Kyoto', 'Osaka'])
Use the atom in your components
import { useAtom } from 'jotai' const [count, setCount] = useAtom(countAtom) <button onClick={() => setCount((c) => c + 1)}>one up</button> const [cities, setCities] = useAtom(citiesAtom) setAnime((cities) => [ ...cities, "new city" ])
JotaiProvider - Server-side rendering
If server-side rendering with a framework such as Next.js or Waku, make sure to add a Jotai Provider component at the root.
// src/components/jotai-provider.tsx "use client"; import { Provider } from "jotai"; interface JotaiProviderProps { children: React.ReactNode; } export const JotaiProvider = ({ children }: JotaiProviderProps) => { return <Provider>{children}</Provider>; }; // src/app/layout.tsx ... return ( <ConvexAuthNextjsServerProvider> <html lang="en"> <body className={`${geistSans.variable} ${geistMono.variable} antialiased`} > <JotaiProvider> {children} </JotaiProvider> </body> </html> </ConvexAuthNextjsServerProvider> ); ...