DEV Community

Dennis Cual
Dennis Cual

Posted on • Updated on

Fun to use state management for your React

When managing your React state, your state manager should only give you simple works to do the job even though that you are maintaining huge state. small is the new big. Yes indeed! It must only give you small utilities to manage it and will be sufficed. It means that it must have minimal API.

easy-react-state gives you this kind of features and use it in fun and easy way. It is like bigger version of React.useState hook but managing different state. It also has smaller API surface so you don't need to learn many stuffs just to make it right.

Let's take a look on how we can use the awesome library:

1 - Configuring your store

NOTE: easy-react-state uses immerjs. So when updating a state, you can use any syntax. This is very handy especially if you change nested property's value. You can use mutator syntax just like state.user.name = 'Zion'.

const configAppStore = {
  todos: {
    initialState: [],
    setters: state => ({
      addTodo(todo) {
        state.push(todo)
        return state
      },
    }),
  },
}

2 - Creating state manager based on your store

NOTE: The returned useSelector will subscribe to the store based on the data which user need and will only re-render the Consumer Component if and only if the subscribed data will change even though the root state gets updated.

const [useAppSelector, appSetters] = createStateManager(configAppStore)

3 - Consume to your React Component

NOTE: We don't need a Provider to consume the store. Just create a manager, then you can use it directly.

const App = () => {
  const todos = useAppSelector(state => state.todos)
  console.log('todos', todos)
  return (
    <div>
      <h3>Todos Control</h3>
      <button
        onClick={() => {
          const todo = {
            id: `todo-${Date.now()}`,
            label: `Todo ${Date.now()}`,
          }
          appSetters.todos.addTodo(todo)
        }}
      >
        Add todo
      </button>
    </div>
  )
}

Pretty simple right? How about async updates? This is easy.

Because the setters are just object which are created outside the Component, then you can call it wherever you want. For an instance, call it inside async function:

const [useAppSelector, appSetters] = createStateManager(configAppStore)

async function fetchUsers() {
  appSetters.users.loading()
  try {
    const res = await apiUsers()
    appSetters.users.setUsers(res)
  } catch (err) {
    appSetters.users.setError(err)
  }
}

And thats it! If you are interested and want to try, you can check its github repo for more info. Of course, it is open-source and feel free to give feedbacks and contribute!

Top comments (0)