jotai

Posted by neverset on December 23, 2020

Jotai is a state management library for React that will save you from boilerplate tears with its minimalistic API(when implementing Redux is the amount of boilerplate code that you need to write in order to handle the data flow between components and the Redux store) difference between redux and Jotai can be seen in following pics:

installation

#install
npm install jotai
# or
yarn add jotai

usage

#state information are stored in atom object
import { atom } from 'jotai'
const countAtom = atom(0)
const countryAtom = atom('Japan')

#the atoms are stored in Jotai's Provider
import { Provider } from 'jotai'
const Root = () => (
<Provider>
    <App />
</Provider>
)

#access the atoms by using the useAtom hook
import { useAtom } from 'jotai'

function Counter() {
const [count, setCount] = useAtom(countAtom)
return (
    <>
    <h1>{count} </h1>
    <button onClick={() => setCount((value) => value + 1)}>one up</button>
    </>
);

refactor redux to Jotai

provider

import { createStore } from "redux";
import { Provider } from "react-redux";
import App from "./App";const store = createStore(reducer);const Main = () => (
<Provider store={store}>
    <App />
</Provider>
)
==>
import { Provider } from "jotai";
import App from "./App";const Main = () => (
<Provider>
    <App />
</Provider>
)

store

const defaultState = {
    isPrimary: true,
};
const reducer = (state = defaultState, action) => {
    // rest of the code omitted...
}
==>
import { atom } from "jotai";
export const isPrimaryAtom = atom(true)

dispatch and action

import { useSelector, useDispatch } from "react-redux";function App() {
const isPrimary = useSelector((state) => state.isPrimary);
const dispatch = useDispatch();const title = isPrimary ? "Primary" : "Secondary";return (
<StyledButton
isPrimary={isPrimary}
onClick={() => {
    dispatch({ type: "TOOGLE_BUTTON", payload: !isPrimary });
}}
==>
import { useAtom } from "jotai";
import { isPrimaryAtom } from "./Atoms";function App() {
const [isPrimary, setIsPrimary] = useAtom(isPrimaryAtom);const title = isPrimary ? "Primary" : "Secondary";return (
<StyledButton
isPrimary={isPrimary}
onClick={() => {
    setIsPrimary(!isPrimary);
}}