Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and why to useEffect

This may seem like a weird question, but I do not really see many use cases for useEffect in React (I am currently working on a several thousand-lines React codebase, and never used it once), and I think that there may be something I do not fully grasp.

If you are writing a functional component, what difference does it make to put your "effect" code in a useEffect hook vs. simply executing it in the body of the functional component (which is also executed on every render) ?

A typical use case would be fetching data when mounting a component : I see two approaches to this, one with useEffect and one without :

// without useEffect
const MyComponent = () => {
    [data, setData] = useState();
    if (!data) fetchDataFromAPI().then(res => setData(res));

    return(
        {data ? <div>{data}</div> : <div>Loading...</div>}
    )
}
// with useEffect
const MyComponent = () => {
    [data, setData] = useState();
    useEffect(() => {
    fetchDataFromAPI().then(res => setData(res))
    }, []);

    return(
        {data ? <div>{data}</div> : <div>Loading...</div>}
    )
}

Is there an advantage (performance-wise or other) to useEffect in such usecases ?

like image 247
Ewaren Avatar asked Nov 06 '22 10:11

Ewaren


1 Answers

I. Cleanup

What if your component gets destroyed before the fetch is completed? You get an error.

useEffect gives you an easy way to cleanup in handler's return value.

II. Reactions to prop change.

What if you have a userId passed in a props that you use to fetch data. Without useEffect you'll have to duplicate userId in the state to be able to tell if it changed so that you can fetch the new data.

like image 90
marzelin Avatar answered Nov 12 '22 21:11

marzelin