I'm making a custom hook that have a toogle when some state change.
You should be able to pass any state in an array.
import { useState, useEffect } from 'react'
const useFlatListUpdate = (dependencies = []) => {
const [toggle, setToggle] = useState(false)
useEffect(() => {
setToggle(t => !t)
}, [...dependencies])
return toggle
}
export default useFlatListUpdate
And it should be used as
const toggleFlatList = useFlatListUpdate([search, selectedField /*, anything */])
But it gives me the following warning
React Hook useEffect has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies.eslint(react-hooks/exhaustive-deps)
I also have another situation where it doesn't work
const useFlatListUpdate = (dependencies = []) => {
const [toggle, setToggle] = useState(false)
useEffect(() => {
setToggle(t => !t)
}, dependencies)
return toggle
}
This gives me the warning
React Hook useEffect was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies.eslint(react-hooks/exhaustive-deps)
How can I make this work without the warning and without disabling eslint?
What is the React UseEffect? The useEffect hook has superpowers that enable us to design our custom hooks. When a change occurs, it allows us to perform side effects in functional components. It allows data retrieval, DOM modification, and function execution each time a component renders.
Why and When To Use Custom Hooks. The main reason to write a custom hook is for code reusability. For example, instead of writing the same code across multiple components that use the same common stateful logic (say a “setState” or localStorage logic), you can put that code inside a custom hook and reuse it.
Use of dependency list is very peculiar in this case.
I do not see other way except ignoring or silencing the warning.
To silence the warning, we do not have to disable eslint
completely.
You can disable this specific rule for this specific line:
const useFlatListUpdate = (dependencies = []) => {
const [toggle, setToggle] = useState(false)
/* eslint-disable react-hooks/exhaustive-deps */
useEffect(() => {
setToggle(t => !t)
}, [...dependencies])
return toggle
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With