Eslint problem in Reactjs with useEffect, in this case how do I not need to put the // Eslint-disable-line

Asked

Viewed 92 times

-2

Well, folks, I have a function that allows for some variables within it. However, it should only be executed when a dependency specific to it is changed. in the case of index

useEffect(() => {
    setRows([])

    const max = index === pages ? data.length : index * range 

    for (let i = index * range - range; i < max ; i++) {
        setRows(oldElemets => [...oldElemets, data[i]])
    }

}, [index])

  • And...? More detail your question.

  • I explained, it turns out that within that useEffect there are several variaves, but in fact I just need that function to be re-established when the index changes. And Eslint keeps giving Warning that there are other variables within the function and asks to add in the dependencies array of useEffect. However as I said only what matters is whether the index has changed. and wanted to avoid using the comment // Eslint-disable-line pro Waring exit.

1 answer

0

The purpose of the rule exhaustive-deps linter, is to prevent Hooks from reading obsolete component properties or states.

As much as other dependencies don’t change during rendering, linter doesn’t know and can’t guarantee it.

As a general rule, all variables and methods would need to be declared within the dependency array in order for linter to be able to ensure that the effect will always be executed using the most recent values of these variables and thus no longer occur Warning.

An alternative would be to use hook useCallback as support, to ensure that your function always receives updated data (but still, all variables would need to be declared as dependencies):

    import {useCallback} from 'react'
    ... 

    const funcao = useCallback((index) => {
        setRows([])
        const max = index === pages ? data.length : index * range 
        for (let i = index * range - range; i < max ; i++) {
            setRows(oldElements => [...oldElements, data[i]])
        }
    }, [pages, data, range]) // garante que pages, data e range sempre estarão atualizados

    useEffect(() => {
        funcao(index)
    }, [index, funcao]) // garante que index e funcao sempre estarão atualizados

One should be very careful in this case, because the rule eslint-disable-line can lead to no reporting situations that can lead to unexpected behavior in the application. The ideal is to somehow pass all dependencies to ensure that the effect does not use obsolete properties or states.

  • What happens is that if I put all the department he is asking for happens a 'Maximum update Depth'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.