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)
>Solution :
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;