Home > Web Front-end > JS Tutorial > body text

Simplify React State Management: Best Practices for Handling Status

王林
Release: 2024-09-10 11:04:07
Original
574 people have browsed it

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>
        </>
    );
};
Copy after login

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 });
Copy after login

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>
        </>
    );
};
Copy after login

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>
        </>
    );
};
Copy after login

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 = async () => {
        setStatus('loading');
        try {
            const user = await api.getUser();
            setUser(user);
            setStatus('success');
        } catch (e) {
            setStatus('error');
        }
    };

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

    return (
        <>
            {status === 'loading' && <div>Loading...</div>}
            {status === 'error' && <div>Error...</div>}
            {status === 'success' && <div>{user?.name}</div>}
            <button onClick={fetchUser}>Fetch</button>
            <button onClick={reset}>Reset</button>
        </>
    );
};
Copy after login

This is a very simple example.
And you can understand the status easily.

When you have to add a new status, you can add a new status easily.
Of course there are cons in this example.
You cannot express the status in the loading and success status in the same time.
But I thought this is not a big problem.

So if you manage the status in the react state, I recommend to use the string to express the status.

Conclusion

When you manage the status in the react state, use the string to express the status.

This is very simple and easy to understand.
And you can add a new status easily.

If you use the object or index to express the status, you have to update all the status when you add a new status.
So, I recommend to use the string to express the status.

Thank you for reading.

The above is the detailed content of Simplify React State Management: Best Practices for Handling Status. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template