starscape
starscape

Reputation: 2973

Should you pass setter functions into the dependency array of a React hook?

Recently I saw a few examples of passing setter functions into hook dependency arrays in my coworkers' React code, and it doesn't look right to me. For example:

const MyComponent = () => {
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    doSomeBigLongNetworkRequest();
    setLoading(false);
  }, [setLoading, /* other deps */]);
  // ...
}

My feeling is that they have misunderstood the purpose of the dependency array, which, as I understand it, is to indicate which pieces of state to monitor so that the hook can fire again when they change, not to simply indicate that the hook needs to use the setLoading function. And since the setLoading function never actually changes, including it in the dependencies does nothing.

Am I correct, or does including the setter in the array make sense somehow? My other thought was that maybe this was just a linter error, since the linter cannot recognize that the function is a setter, and thinks it might change.

I should also add that in the instances I've seen, they've included the setter but not the variable. So in the example above, setLoading, but not loading would be in the dependency array, and the hook does not actually need the value of loading.

Upvotes: 34

Views: 6311

Answers (2)

  • React team suggest that we don't have to pass setState function in the dependency array of useCallback in the same component level, but we can still pass all props that come to child component as a dependency array in the useCallback of the child component.

  • If we miss any of the prop event handlers to add them in the dependency array, as parent component renders - it sends the event handlers as prop, the child component sees them as a new function and its also re-renders. Even though we are passing the same definitions for event handlers, as we know that (this of prev function != this of current function), that's why the child component also re-renders.

  • Hence finally we can pass the props of the child component as dependency array but we should pass the child component setState functions to the dependency array of useEffect or useCallbacks.

Now, React team has come up with new suggestion "useEffectEvent", but it was not released. I just tried a snippet to give you an understanding of how the dependency are handled below.

import { experimental_useEffectEvent as useEffectEvent } from 'react';


function ParentComponent(){
    const [message, setMessage] = useState('initial message');
    // other logics 
  return (
       <>
        <ChildComponent message={}  newMessage={} setMessage={} />
      </>
    );
}

function ChildComponent({message, newMessage, setMessage}){
    const onChangeHandler = useEffectEvent(()=> {
      setMessage(newMessage);
    });
    
    const handleInputChange = useCallback(()=>{
       if(message != newMessage){
         onChangeHandler();
    }}, [message, newMessage]); // setMessage is not needed here, as we have useEffectEvent

   return (
       <>
            {/* child compoent markup */}
       </>
);
}

Upvotes: 0

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

In general yes you are right there is no need to include them. Here is quote from docs:

React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.

However if useState is passed as prop you might have to use it as dependency. Below quote explains that (it uses refs as example but is should apply to useState too because they are both always-stable dependencies):

Omitting always-stable dependencies only works when the linter can “see” that the object is stable. For example, if ref was passed from a parent component, you would have to specify it in the dependency array. However, this is good because you can’t know whether the parent component always passes the same ref, or passes one of several refs conditionally. So your Effect would depend on which ref is passed.

Upvotes: 32

Related Questions