Home > Software design >  Parameters for anonymous function in React JS
Parameters for anonymous function in React JS

Time:11-14

In the React Navigation documentation for Header Buttons, there is a code that creates a function that updates the "count" state.

const [count, setCount] = React.useState(0);

<Button onPress={() => setCount((c) => c 1)} title="Update count" />

demo link from documentation

I assume that the variable c is supposed to be the current count in the anonymous function that is created for onPress. However there is no reference to c elsewhere in the code.

Where is the value of c coming from and how is it being linked to count state?

CodePudding user response:

The setState return setter function from useState automatically passes the previous value of the state to a function passed to setState.

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount   1)}> </button>
    </>
  );
}

CodePudding user response:

When you pass a function to a state updater like you're doing here, React invokes that function with the current value.

c is being passed in by React. (It's just a regular function parameter so you can name it whatever you want.)

CodePudding user response:

I think that the easiest and most friendly explanation would be to compare it with Array#map function. Arrat#map is a higher-order function - it means that it takes other function as the argument/parameter.

[1, 2].map((item) => item   1); // [2, 3]
        // ^^^^^^^^^^^^^^^^^^^ this is the callback function

The same situation with the setState function (in your example - setCount) - it takes a function as argument. A function that works the same as the function passed above to the Array#map, with that difference that in Arrat#map the item parameter is the currently iterated element of the array, but in the state setter function, item (or c in your case) will stand as the current value of the state (of count in your case).

setCount((c) => c   1);
  //     ^^^ current value of `count`

Then, React simply invokes the function you have passed with current state value. That's it.

  • Related