Home > database >  Why does React/Typescript complain want me to use my return function in useEffect dependency array?
Why does React/Typescript complain want me to use my return function in useEffect dependency array?

Time:08-08

I'm making a checkbox component for my project, and I have it set so that whenever is isChecked state changes, useEffect will run a returnFunction (defined in the props), like so:

export function JCheckbox({ returnFunction }: JCheckboxProps) {


const [isChecked, setIsChecked] = React.useState(defaultState)

React.useEffect(() => {
    returnFunction(isChecked)
}, [isChecked])

When I do this, my compiler wants me to include returnFunction in the useEffect dependency array. I'm confused why I would need to track that, it's not used at all anywhere else in the function, and it doesn't change either. The code works perfectly fine without it.

CodePudding user response:

You should add your function (returnFunction) to useEffect dependency because your function reference (returnFunction) may be changed, So react ask you to add your function (returnFunction) in useEffect dependency to recognize that and update them by new function reference.

CodePudding user response:

returnFunction is certainly used as it is called inside the effect, and it could certainly change as the parent component could pass in different props, in which case your component would continue to call the previously passed in function. So the linter is correct, returnFunction is a dependency. However adding it makes it slightly more difficult to detect changes of isChecked, as changing returnFunction would also trigger the effect. Thus it seems way more elegant to call returnFunction from within setIsChecked:

const [isChecked, _setIsChecked] = useState(false);

function setIsChecked(value: boolean) {
  returnFunction(value);
  _setIsChecked(value);
}

However in the case given it seems that the state should rather be maintained by the parent component, consider lifting it up.

CodePudding user response:

returnFunction is read from props so you probably must include it in the array of dependencies.

You should almost always include every variable and function you declare inside React and use in useEffect callback in the array of dependencies.

Eslint does not expect you to include setState functions and refs that you create in the same component that you execute useEffect.

Edit:

If you have a handleChange event handler and isChecked is toggled whenever the onChange method is invoked, you probably do not need useEffect. Call returnFunction function with the new isChecked value.

  • Related