DEV Community

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

Posted on • Edited on

1

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

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay