Migrate state management from Redux to Jotai

With Redux

There are really a lot of codes. Dig in each files to check the detail.

  • actions category.js

  • component category.js

      import { useSelector, useDispatch } from "react-redux";
      import { setCategory, initCategory, setCategoryName, setCategoryStatus } from '../../actions/category';
    
      const Category = props => {
    
        const { category, status } = useSelector(state => {
          return state.category
        });
    
        const dispatch = useDispatch();
    
        dispatch(...);
        dispatch(...);
        dispatch(...);
        ...
    
      }
  • Provider with store to wrap around App.

      import { Provider } from "react-redux";
      <Provider store={store}>
        <App />
      </Provider>

With Jotai

It's much simple. I only initialize the default state value, then just call with useAtom() Basically, both reducers and actions are not necessary any more.

  • Define store category.js

      import { atom } from "jotai";
    
      const initialCategoryListState = []
    
      export const initialCategoryState = {
          id: 0,
          name: "",
          status: ""
      }
    
      export const categoryListAtom = atom(initialCategoryListState)
      export const categoryAtom = atom(initialCategoryState)
  • State in the component Category.js

      import { useAtom } from "jotai";
      import { categoryAtom, initialCategoryState } from "../../store/category";
    
      const Category = props => {
    
      const [category, setCategory] = useAtom(categoryAtom);
      ...
      }
  • Provider with store to wrap around App.

    import { Provider } from "jotai";
    
      <Provider store={store}>
        <App />
      </Provider>

Advanced Jotai

  • Use atom to load data. Move away the code to load from Component.

Last updated