Simplify your React state management with react-state-factory
Tags: react, opensource, typescript, discuss
Published: 2023-09-13 10:26:15

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:

```sh
npm add react-state-factory
```

## Usage

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

```ts
// 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",
};
```

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

Time to make state, and reducer:

```ts
// 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;
}
```


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

```tsx
// 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>
  );
}
```

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?](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m0w2nlnhzypafw9xg8oy.jpeg)

## 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](https://www.npmjs.com/package/react-state-factory?activeTab=readme)

> images created with [clipdrop.co](https://clipdrop.co/stable-diffusion?output=true)