Search code examples
javascriptreactjsuse-effectreact-propsreact-functional-component

React Hook useEffect has a missing dependency: 'props' due to one line in useEffect


In my react app, there is a useEffect. This is my code:

useEffect(() => {
        const trimmedArray = trimArray(props.firstInputValue);
        props.setFirstFinalSetArray(trimmedArray);
        setFirstPrintArray(`{${trimmedArray.join(', ')}}`);
    }, [props.firstInputValue]);
  1. This useeffect is used in a functional component.
  2. trimArray is a function
  3. setFirstFinalSetArray is a useState set function.
  4. setFirstPrintArray is state in current component.
  5. firstInputValue is state in parent component.

And I found due to this line : props.setFirstFinalSetArray(trimmedArray); I am getting this error: React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps


Solution

  • You can destructure your props like:

    const MyComponent = ({firstInputValue, setFirstFinalSetArray}) => {
      const [firstPrintArray, setFirstPrintArray] = useState()
      useEffect(() => {
        const trimmedArray = trimArray(firstInputValue);
        setFirstFinalSetArray(trimmedArray);
        setFirstPrintArray(`{${trimmedArray.join(', ')}}`);
      }, [firstInputValue, setFirstFinalSetArray]);
    
      // rest of your code
    }
    

    When I was learning React I was hesitant to do this for whatever reason (I liked having props I guess), but it really does make for clean code.