1

I have the following block of code:

function foo({ bar, func }) {
  useEffect(() => {
    func(bar)
  }, [func, bar])

  ....
}

Is this an anti pattern to include func within the dependencies list for React.useEffect? I'm under the impression that the function definition for func almost never changes. Please correct me if I'm wrong.

kdizzle
  • 577
  • 1
  • 11
  • 23

1 Answers1

2

This depends on the value of func that is obviously initialized in the parent component

But assuming func is set to a constant function that will never change (which is mostly the case) then no need to add it here, you could just leave bar and remove func from the second argument of useEffect

However the bad practice here, in your code if func is set to a function that increments bar for example

const func = (bar) => bar + 1;

This will end up triggering the useEffect infinitely, because everytime bar changes the useEffect will be triggered and increment bar again and so on.

In case you're wondering if func can ever be changed

I'll give you an example parent component that func will change on a button click.

import React, {useState} from "react";

const ParentComponent = () => {
    const increment = bar => bar+1;
    const decrement = bar => bar-1;

    const [func, setFunc] = useState(increment);

    return <div>
         //When this button is clicked, `func` value will be changed
         <button onClick={() => setFunc(decrement)}/>

         // This is your component
         <foo func={func}/>
    </div>
}
Ali Elkhateeb
  • 3,413
  • 4
  • 21
  • 39