DEV Community

Cover image for useState() React Hooks(P1)
Danijela.js๐Ÿ›ธ
Danijela.js๐Ÿ›ธ

Posted on โ€ข Edited on

useState() React Hooks(P1)

Hooks are special functions that let you โ€œhook intoโ€ React features. They donโ€™t work inside classes, just in functional components.
useState() lets you add state to a functional component.

  • Always use hooks at the beginning of a React function.
  • Don't call hooks inside loops, conditions or nested functions.
  • You can use multiple useStates and variables.
  • The only argument we pass to useState() is the initial value.
  • useState() is returning the variable and the function that updates it.

Now, a basic counter example:

Alt Text

Explanation:

We have to import the useState() hook.

As you can see, we have a variable called count, and a function that updates that variable, setCount(). The initial value of the count is 0.

We are displaying the count in a h1 tag.

The first button has a click event that fires the setCount() function, which will add 1 on every click.

The second button is using the same function on click, but this time, it's going to subtract 1.

And this is the end result:

Alt text of image

I hope I helped at least one person :)

Top comments (7)

Collapse
ย 
emmabostian profile image
Emma Bostian โœจ โ€ข

Nice post!! You can also combine the react default and named imports like this!

import React, {useState} from โ€œreactโ€

Iโ€™m on my phone so sadly no back ticks. But nice job!!

Collapse
ย 
emmabostian profile image
Emma Bostian โœจ โ€ข

Also might be worth noting that the hooks have to be the first thing in the function :) that confused me when I was starting!

Collapse
ย 
danijelajs profile image
Danijela.js๐Ÿ›ธ โ€ข

You are right, I'll add that to the article! ๐Ÿ˜Š

Collapse
ย 
danijelajs profile image
Danijela.js๐Ÿ›ธ โ€ข

Thanks! Yeah, I know, it's just "a thing" I do without even thinking about it. ๐Ÿ˜…

Collapse
ย 
raajsteve profile image
Rajkumar โ€ข

Thanks for sharing

Collapse
ย 
mohsin708961 profile image
{{7*7}} โ€ข

Awesome

Collapse
ย 
danijelajs profile image
Danijela.js๐Ÿ›ธ โ€ข

Thanks!๐Ÿ™๐Ÿ˜Š