DEV Community

Cover image for Simplify your React state management with react-state-factory
Peter Vivo
Peter Vivo

Posted on • Edited on

Simplify your React state management with react-state-factory

Hello fellow developers! If you have been working with React for some time, you would know that managing state can get complicated as your application grows. There are several libraries available for state management, like Redux and MobX, but sometimes they can be a bit too much for small to mid-sized applications.

Today, I want to introduce you to a new library called react-state-factory. This minimal library helps to organize mid-complex state handling with type-guarded dispatch capable actions. It is built using TypeScript, useReducer hook, and redux-saga, making it type-safe and efficient.

Installation

You can install react-state-factory via npm:



npm add react-state-factory


Enter fullscreen mode Exit fullscreen mode

Usage

First, you need to declare a set of actions with their types:



// actions.ts

export type ActionMap =
  | { type: "START_APPLICATION", payload: { start: number, id: string } }
  | { type: "PLACE_CONTENT", payload: number[] }
  | { type: "ADD_ITEM", payload: number }

// enough write first line with value of {}, rest is generated 
// by VS Code Quick Fix
export const actions: Labels<ActionMap> = {
  START_APPLICATION : "START_APPLICATION",
  PLACE_CONTENT : "PLACE_CONTENT",
  ADD_ITEM : "ADD_ITEM",
};


Enter fullscreen mode Exit fullscreen mode

Here, we have defined three actions: START_APPLICATION, PLACE_CONTENT, and ADD_ITEM, each with their respective payloads.

Time to make state, and reducer:



// reducer.ts

export type SimpleState = {
  id: string;
  start: number;
  content: number[];
}

export const initialState:SimpleState = {
  id: "", start: 0, content: []
};

// at this moment VS Code help to select valid case strings, and every where do you know the payload type depend on case.
export const reducer: Reducer<SimpleState, ActionsMap> = (state,  { type, payload }) => {
  switch (type) {
  case "START_APPLICATION": return {...state, id: payload:id, start: payload: start };
  case "PLACE_CONTENT": return {...state, content: payload };
  case "ADD_ITEM": return {...state, content: [...state.content, payload]};
};
  default: return state;
}


Enter fullscreen mode Exit fullscreen mode

Now, you can use the useStateFactory hook in your component:



// SimpleComponent.tsx
export const SimpleComponent: FC = () => {

  const [state, put] = useStateFactory(reducer, initialState, actions);

  useEffect(() => {
    put.START_APPLICATION({
      start: Date.now(),
      id: "-basic-app-uui-",
    });
  }, [put]);

  const handleExtendContent = () => put.ADD_ITEM(Math.random() * 100 | 0);

  return (
    <main className="bg-black text-green-400 min-h-screen grid place-items-center relative">
      <button onClick=(handleExtendContent)>add item</button>
      <pre>{JSON.stringify(state, null, 2)}</pre>
    </main>
  );
}


Enter fullscreen mode Exit fullscreen mode

In this example, put is an object with methods corresponding to each action. You can call these methods with the required payload to dispatch the corresponding action.

Similarly, you can use the typedPutActionMapFactory and useSagaFactory for handling side effects using redux-saga.

ask your co-ai

co-ai helps a lot or not?

Conclusion

react-state-factory is a minimal and type-safe library for managing state in React applications. It leverages TypeScript, useReducer, and redux-saga to provide a simple and efficient way to handle state and side effects. Give it a try and let me know your thoughts in the comments below!

Be the first who is try it: react-state-factory

images created with clipdrop.co

Top comments (0)