2
function foo1() {
return {
bar: "hello"
};
}
function foo2() {
return {
bar: "hello";
}
}

There is two functions 'foo1' and 'foo2' what will be the possible output and what is key difference between these functions.

Kumar Shivam
  • 137
  • 1
  • 9

1 Answers1

5

Preface: As shown, both will cause infinite re-renders. The setState calls should only be in reaction to something else happening.

setState(state + 1) uses the in-scope value of state (which might be stale), adds one, and sets that as the new value. If state is stale (the actual state value has been updated in the meantime), that will overwrite a previous update.

setState(state => state + 1) asks setState to call it back with the guaranteed-up-to-date version of state, adds one to it, and then sets that as the value.

Either is fine in an appropriate situation, but typically you want the second (callback) form, not the first, when updating state based on existing state.

More here in the React documentation.

Here's a contrived example demonstrating the difference using a stale state1 value:

const {useState, useEffect} = React;

const Example = () => {
    const [state1, setState1] = useState(0);
    const [state2, setState2] = useState(0);
    
    useEffect(() => {
        const timer = setInterval(() => {
            // THIS IS INCORRECT (for this situation), it uses a stale value
            // of `state1`
            setState1(state1 + 1);
            
            // This is correct (for this situation)
            setState2(state2 => state2 + 1);
        }, 500);
        return () => {
            clearInterval(timer);
        };
    }, []);
    return <div>
        <div>state1 = {state1}</div>
        <div>state2 = {state2}</div>
    </div>;
};

ReactDOM.render(<Example />, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

There are some tools (like ESLint w/appropriate plugins) that will warn you about some situations where you're using stale state variables; for instance, ESLint's exhaustive-deps rule from eslint-plugin-react-hooks would issue a warning above that state1 was missing from the useEffect dependencies array.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875