Omit function props from the dependencies list in React.useEffect?

99封情书 提交于 2021-01-28 07:32:27

问题


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.


回答1:


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>
}


来源:https://stackoverflow.com/questions/58759239/omit-function-props-from-the-dependencies-list-in-react-useeffect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!