I have a function that sets my useState when on click, everything works fine but I am getting a warning everytime:
Line 22: The 'handleClickOpen' function makes the dependencies of useEffect Hook (at line 20) change on every render. To fix this, wrap the 'handleClickOpen' definition into its own useCallback() Hook react-hooks/exhaustive-deps
this is my code:
useEffect(() => {
axios.get("/api/getBlacklist/").then(data => setBlacklistItems(data.data));
// eslint-disable-next-line
}, [handleClickOpen]);
function handleClickOpen() {
setOpen(true);
}
I have tried to replace handleClickOpen
in useEffect
with just setOpen(true)
, but then my page crashes because of too many re-renders.
How to deal with this situation?
useEffect(callback, dependencies) is the hook that manages the side-effects in functional components. callback argument is a function to put the side-effect logic. dependencies is a list of dependencies of your side-effect: being props or state values.
The useEffect Hook allows you to perform side effects in your components. Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments. The second argument is optional.
The warning "React Hook useEffect has a missing dependency" occurs when the useEffect hook makes use of a variable or function that we haven't included in its dependencies array. To solve the error, disable the rule for a line or move the variable inside the useEffect hook.
Dependency arrays are a concept that is tightly coupled to hooks in React (thus also to function components). Some hooks, like useEffect and useCallback have 2 arguments. The first one is a callback (a function), and the second one is the dependency array. It takes the form of an array of variables.
Every render it will create new handleClickOpen
function. You can memoize it by useCallback
import { useCallback } from 'react'
const handleClickOpen = useCallback(() => {
setOpen(true)
}, [])
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