Do props that are functions belong in a useEffect dependencyArray?

Viewed 535

Say I have the following code:

const ReactFunction = ({...props}) => {

useEffect(() => { props.function(props.value) }, [props.value])

return <input value={props.value} onChange={props.onChange} />
}

const ReactFunctionWrapper = () => {

const [value, setValue] = setState(0)
const logger = (e) => {console.log(e}

return <ReactFunction onChange={setValue} value={value} function={function} />
}

Should the function() prop be in the dependencyArray of the useEffect as well even though it's a function and should never change?

What exactly should be going into the dependency array?

3 Answers

Technically, yes. Functions can appear in useEffect's dependency array. Function pointers change on each refresh unless you use some cache feature to cache the function like useMemo or useCallback.

Should the function() prop be in the dependencyArray of the useEffect as well even though it's a function and should never change?

If the function doesn't references any value value from props or state or any other value derived from props or state, only then it is safe to omit that function from the dependency array of the useEffect hook or any other hook that has a dependency array, for example, useCallback.

If the function uses props or state, then it is not safe to omit it from the dependency array. You could wrap the function in useCallback hook to avoid creating new function reference every time the parent component re-renders.

For details on what could happen if you omit a function from useEffect's hook dependency array, see Is it safe to omit functions from the list of dependencies?

There are some functions that are guaranteed to not change and are safe to omit from the dependency array. For example: dispatch function returned by useReducer hook or state update function returned by useState hook. They are safe to omit but still won't hurt if you add them to the dependency array if they are used inside useEffect hook.

What exactly should be going into the dependency array?

Everything in component's scope that participates in react's data flow and is used inside the useEffect hook's callback function. Same is true for useMemo and useCallback hooks.

The 2nd Parameter in React.useEffect() distinct when the effect is invoked. It's when the value of your 2nd Parameter changes, React runs the effect

Go checkout https://youtu.be/dpw9EHDh2bM?t=3629

Related