Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The function makes the dependencies of useEffect Hook

Tags:

reactjs

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?

like image 231
sanna Avatar asked Jun 07 '19 10:06

sanna


People also ask

What are dependencies in useEffect?

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.

What is the function of useEffect ()?

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.

How do I fix React hook useEffect has missing dependencies?

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.

Why do we use array dependency in the useEffect hooks in React?

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.


Video Answer


1 Answers

Every render it will create new handleClickOpen function. You can memoize it by useCallback

import { useCallback } from 'react'

const handleClickOpen = useCallback(() => {
  setOpen(true)
}, [])
like image 130
Giang Le Avatar answered Oct 23 '22 07:10

Giang Le