0

i'm new to React. I followed a tut for making a timer counter. I want to know what is the difference between these lines of code ?
can someone explain what is happening in the first line ?

line1: setSeconds((seconds) => seconds + 1);
line2: setSeconds(seconds + 1)
  • 2
    The first one you are calling a function, with a callback as the parameter, and the second you are calling a function with an number as a parameter – Alexander Jul 19 '22 at 12:20

3 Answers3

1

In React useState hook if you want to set a value directly in state this is how it is done in line2: where seconds can be a variable with some number value such as

const seconds = 0;
setSeconds(seconds + 1) 

If there is a previous value in state that you want to increment, this is how it is done as in line1:

setSeconds((seconds) => seconds + 1);

Here consider it like,

setState((previousValue) => previousValue + 1)

previousValue holds the value which contained in your previous state e.g seconds which in above example was 0, after execution of line 2 it will become 0 + 1 = 1;

For more information

Zain Hasan
  • 26
  • 2
0

In many cases there won't be a functional difference. It depends on whether you're just updating a state value or whether you're queueing a bunch of state value updates.

The former (longer) version updates state based on the state within the queue of state updates. So if you have multiple updates, each one will see the previous update as well and can add to it. The latter (shorter) version updates state directly, based on the value you have at that time.

This can be more effectively illustrated with multiple updates. For example, this code:

setSeconds((sec) => sec + 1);
setSeconds((sec) => sec + 1);

(I've changed the variable name to illustrate that seconds was being shadowed in your example, which is often a bad practice and leads to confusion.) In this case, if the seconds state value was originally 0, then the new state after re-rendering will be 2. Because each state update queued here used the previous update.

But with this code:

setSeconds(seconds + 1);
setSeconds(seconds + 1);

Even though there are still two state updates, the second one has no knowledge of what happened in the first one. Both of them explicitly update state to 0 + 1. So when the component re-renders, even though both of these updates executed, the resulting state value will be 1 instead of 2.


The main takeaway here is that state updates are queued and asynchronous. For simple one-update-and-re-render operations, it doesn't matter. But for more complex operations with potentially multiple updates to state, the callback version is how you would manage those updates.

David
  • 208,112
  • 36
  • 198
  • 279
-1

Line 1 is a call to function that take a callback Line 2 is a call to function that take the variable seconds + 1