DEV Community

Mr-peipei
Mr-peipei

Posted on

Simplify React State Management: Best Practices for Handling Status

Sometimes, we have to manage the status in the react state.
For example, we have a submit form, and we have to manage the status of the form.

There are many way to express the status.
I will introduce the bad example to express status.

Bad example

1. Use the object to express the status.

const Page = () => {
    const [status, setStatus] = useState<{ loading: boolean, error: boolean, success: boolean }>({ loading: false, error: false, success: false });

    const fetchUser = async () => {
        setStatus({ loading: true, error: false, success: false });
        try {
            const user = await api.getUser();
            setStatus({ loading: false, error: false, success: true });
        } catch (e) {
            setStatus({ loading: false, error: true, success: false });
        }
    };

    return (
        <>
            {status.loading && <div>Loading...</div>}
            {status.error && <div>Error...</div>}
            {status.success && <div>Success...</div>}
            <button onClick={fetchUser}>Fetch</button>
        </>
    );
};
Enter fullscreen mode Exit fullscreen mode

This is bad example because the status is very complex.
When you update the status, you have to update all the status.

There are only three status pattern in this example.

// loading
setStatus({ loading: true, error: false, success: false });

// success
setStatus({ loading: false, error: false, success: true });

// error
setStatus({ loading: false, error: true, success: false });
Enter fullscreen mode Exit fullscreen mode

But when you use a object to express the status, reader can't understand that there are only three patterns.
So this is bad example.

2. use index to express the status.

const Page = () => {
    const [status, setStatus] = useState<0 | 1 | 2 | 3>(3);
    const [user, setUser] = useState<User | null>(null);

    const fetchUser = async () => {
        setStatus(0);
        try {
            const user = await api.getUser();
            setUser(user);
            setStatus(2);
        } catch (e) {
            setStatus(1);
        }
    };

    const reset = () => {
        setUser(null);
        setStatus(3);
    };

    return (
        <>
            {status === 0 && <div>Loading...</div>}
            {status === 1 && <div>Error...</div>}
            {status === 2 && <div>{user?.name}</div>}
            <button onClick={fetchUser}>Fetch</button>
            <button onClick={reset}>Reset</button>
        </>
    );
};
Enter fullscreen mode Exit fullscreen mode

This is a very simple example.
But there are also have a problem in this example.

When you use the index to express the status, you have to remember the status number.
If when you have to add a new status, you have to update all the status number.

So, this is also not good example.

3. create state for each status.

const Page = () => {
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<boolean>(false);
    const [success, setSuccess] = useState<boolean>(false);
    const [user, setUser] = useState<User | null>(null);

    const fetchUser = async () => {
        setLoading(true);
        try {
            const user = await api.getUser();
            setUser(user);
            setSuccess(true);
        } catch (e) {
            setError(true);
        }
    };

    const reset = () => {
        setUser(null);
        setLoading(false);
        setError(false);
        setSuccess(false);
    };

    return (
        <>
            {loading && <div>Loading...</div>}
            {error && <div>Error...</div>}
            {success && <div>{user?.name}</div>}
            <button onClick={fetchUser}>Fetch</button>
            <button onClick={reset}>Reset</button>
        </>
    );
};
Enter fullscreen mode Exit fullscreen mode

This is also not good example.
You have to management all the status state in the function all the time.

And if you forget to update the status, it will be a bug.
Reset function is also very complex.

Recommendation

  1. Use the string to express the status.
const Page = () => {
    const [status, setStatus] = useState<'loading' | 'error' | 'success' | 'idle'>('idle');
    const [user, setUser] = useState<User | null>(null);

    const fetchUser