javascriptreactjsreact-hooks

React useCallback/useEffect deps object property usage


Is it correct to include in useEffect/useCallback deps only used props, but not whole object?

For example:

function Component (props) {
  useEffect(() => console.log(props.someValue), [props.someValue]) // ? eslint plugin tells that you should include props, not props.someValue.
  return someVal
}

Solution

  • FYI: props is an object that is passed to component and whatever props you pass it is going to be a property of that object.

    If you want to run callback when props.someValue has changed then you should only provide props.someValue in deps array. Your code will work also with props but there [READ BELOW].

    CODESANDBOX

    Use props.someValue as dependency instead of props

    But problem comes when parent component renders without changing someValue let say there is one more state someValue2 then if that changes then adding props as deps will trigger callback function of useEffect

    As you can see in the following example that props.someValue has changed with props.someValue will only log in console if props.someValue gets changed not when props gets changed

    function Component(props) {
      // ? eslint plugin tells that you should include props, not props.someValue.
      useEffect(() => {
        console.log("props.someValue has changed with props.someValue");
      }, [props.someValue]);
    
      useEffect(() => {
        console.log("props.someValue has changed with props");
      }, [props]);
    
      return (
        <div
          style={{
            backgroundColor: "bisque",
            padding: "1rem",
          }}
        >
          <h1>In Component</h1>
          <h1>{props.someValue}</h1>
          <h1>{props.someValue2}</h1>
        </div>
      );
    }
    
    export default function App() {
      const [someValue, setSomeValue1] = useState(0);
      const [someValue2, setSomeValue2] = useState(0);
      return (
        <div className="App">
          <div
            style={{
              backgroundColor: "lightcoral",
              padding: "1rem",
            }}
          >
            <h1>In Component</h1>
    
            <h1>someValue 1: {someValue}</h1>
            <button onClick={() => setSomeValue1((c) => c + 1)}> + </button>
            <button onClick={() => setSomeValue1((c) => c - 1)}> - </button>
    
            <h1>someValue 2: {someValue2}</h1>
            <button onClick={() => setSomeValue2((c) => c + 1)}> + </button>
            <button onClick={() => setSomeValue2((c) => c - 1)}> - </button>
          </div>
          <Component someValue={someValue} someValue2={someValue2} />
        </div>
      );
    }