Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useEffect to run on both component mounting and dependency change

I want to know how to run the useEffect side effect in both component mounting and a dependent value change. Currently I'm using two useEffects to achieve this like this.

useEffect(() => {
    let isMounted = true;
    const getUsers = async () => {
        try {
            const userResponse = await api.get('/users');
            if (isMounted) { setUsers(userResponse.data); }
        } catch (error) {
            console.log(error);
        }
    };
    getUsers();
}, []);

useEffect(() => {
    let isMounted = true;
    const getUsers = async () => {
        try {
            const userResponse = await api.get('/users');
            if (isMounted) { setUsers(userResponse.data); }
        } catch (error) {
            console.log(error);
        }
    };
    getUsers();
}, [netInfo]);

Is there anyway to achieve this using one useEffect?

like image 615
camille Avatar asked Oct 27 '25 07:10

camille


1 Answers

Runs when the component is mounted for the first time and on every re-render

useEffect(() => {})

Runs when the component is mounted for the first time alone

useEffect(() => {}, [])

Runs when the component is mounted for the first time and whenever the someDependency's value changes .

useEffect(() => {}, [someDependency])

You can remove the first useEffect .

like image 182
Shyam Avatar answered Oct 29 '25 05:10

Shyam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!