Home > Mobile >  Is there any benefit to using more than one useEffect?
Is there any benefit to using more than one useEffect?

Time:09-21

I recently stumbled over some code where two useEffect hooks were used as opposed to one. Is there any difference between using one big function and multiple? The following code does the job, so I guess I'm just curious.

const MyProjects = () => {
    const [data, setData] = useState([])
    const [dataLoaded, setDataLoaded] = useState(false)
    let clone = useRef(null);

    async function fetchData() {
        await fetch('https://jsonplaceholder.typicode.com/todos')
        .then(response => response.json())
        .then(json => {
            setData(json)
            clone.current = [...json]
            setDataLoaded(true)
        })
        // .then(setData(data.map((item) => ({...item, backgroundColor: true}))))
        .catch((err) => {
            console.log(err);
          });
    }

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

    useEffect(() => {
        if (!dataLoaded) return
        const newArray = clone.current.map(item => (
            {...item, backgroundColor: 'orange'}
        ))
        // console.log(clone.current)
        setData([...newArray])
        console.log(data)
    }, [dataLoaded]);

CodePudding user response:

Like all things in programming, the answer is still the same, it honestly depends on the use case.

Case 1: Separating for functionality

The code you have given demonstrates this use case. In your code, the first useEffect is used to fetch the data. This has an empty dependency list and so it will only run once on mounting ( First Render ).

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

While the second useEffect will run but return on the First Render, and only run again each time the dataLoaded variable is mutated

useEffect(() => {
    if (!dataLoaded) return
    const newArray = clone.current.map(item => (
        {...item, backgroundColor: 'orange'}
    ))
    // console.log(clone.current)
    setData([...newArray])
    console.log(data)
}, [dataLoaded]);

Now it makes sense to keep both functionalities separate because if you kept them together. Then on each data modification, fetchData would've run again. So yes there is a functional benefit in separating useEffects depending on which code you want to run on dependency changes.

Case 2: Separating for code readability and debugging

Usually if you have a useEffect that has too many lines of code. It is better to separate them into different useEffects grouping same purpose code into different useEffects. This will help in code readability and easier debugging afterwards.

  • Related