Original address: medium.com/better-prog… Translation address: github.com/xiao-T/note… The copyright of this article belongs to the original author. Translation is for study only.


Do we still need state management frameworks like Redux and Mobx?

The introduction

The introduction of React hooks has changed the reality of state management.

Previously, it was difficult to share state-related logic between components. Now, we can do this simply by abstracting a hook (for example, useUserLogin).

This begs the question, why do we still need a state management framework? In this article, I will show my decision making process: how to manage state. I will also share my views on whether we still need a state governance framework in 2020.

What has changed?

How did we define state before Hooks? Basically, there are two options: define local state inside the component, or use a state management framework to set global state (e.g. Mobx/Redux).

Local state (before hooks)

export class UserList extends Component {
    state = {
        isLoading: false.hasError: false.users: []
    }

    searchUsers(value) {
        this.setState({isLoading: true});

        api.get(`/users? searchKey=${value}`)
            .then((data) = > this.setState({users: data}))
            .catch((a)= > this.setState({hasError: true}))
            .finally((a)= > this.setState({loading: false}));
    }

    render() {
        if (this.state.isLoading) {
            // render loading spinner
        }
        
        if (this.state.hasError) {
            // render error message
        }

        return (
            <div>
                <input onChange={(event)= > this.searchUsers(event.target.value)} />
            </div>)}}Copy the code

We’ll explain the problems that arise when there are only two options. Let’s say our state doesn’t have to be global, but we want to reuse state across multiple components. How do we define local state?

In the above demo, we might want to reuse loading and error state, not before Hooks. The only option is to reuse it using Redux. In Redux, any component that needs to search for users can simply dispatch an action (searchUsers()) and listen for global state changes.

However, using these global states (Redux/Mobx) causes some problems:

  • More boilerplate code
  • Complex data flow
  • Multiple components maintaining global state at the same time can have unintended side effects.

React Hooks!

Thank goodness for the Hooks introduced in React V16.8. From this point on, it becomes feasible to share state-related logic between components.

In the following demo, we can share the behavior of loading and error:

import {useState} from 'react';

const useRequestHandler = (a)= > {
    const [isLoading, setLoading] = useState(false);
    const [hasError, setError] = useState(false);
    const [data, setData] = useState(null);

    const handleRequest = (request) = > {
        setLoading(true);
        setError(false);

        return api.get(request)
            .then(setData)
            .catch((a)= > setError(true))
            .finally((a)= > setLoading(false))};return {isLoading, hasError, data, handleRequest};
};


const UserList = (a)= > {
    const {data, isLoading, hasError, handleRequest} = useRequestHandler();
    
    const searchUsers = (value) = > handleRequest(`/users? searchKey=${value}`);
  
    return (
        <React.Fragment>
            {data.map(u => <p>{u.name}</p>)}
        </React.Fragment>)}Copy the code

More benefits: If multiple components need the ability to search user lists, we can also customize useUserSearch Hook.

Hooks, however, are not silver bullets. Storing state in a hook does not make it a singleton, it is just tied to a component. In some cases, we want to keep only one instance state object (for example, only load user information once). This is what the State management framework provides.

How, when, and where to manage state

Now that state-related logic can be shared among multiple components, how do we decide whether state is stored within the component (local) or in the state management framework (global)?

The picture below shows my decision making process.

What are the benefits of a State management framework?

Now we know how to make choices globally and locally. But why do we need a state governance framework in 2020? How is this better than React Hooks?

It has the following advantages:

  • Global definition, which also means that there is only one instance object
  • Remote data is loaded only once
  • Development tool support
  • Provides a standard development approach for software engineers

conclusion

We’ve seen React Hooks roil the state management landscape. Thanks to their introduction, sharing state-related logic between components becomes simpler.

However, Hooks are not a silver bullet and we still need a state management framework. This does not mean that all state should be global either — in most cases it is better to keep it between components. Move state into the state management framework only when absolutely necessary.