Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the diference between these lines?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading