React Hooks: useState

React Hooks: useState

My cat, Rambo, being 'hooked'

Normal react code would use a class component and use this.setState to manage the state.

Hooks is a way to write functional components but use state inside of them like you would a class component.

First, import the hook you want to use from React.

useState gives us back two parameters inside of an array. Use array destructuring to declare, in this order, state value, and the function that will modify that state value. You can name these two items whatever you want (you’re just declaring variables here), so make the names explicit. E.g., if you wanted to set the name to the logged in user, a simple example would be like the below, where the name is being modified by the function setName, and useEffect is setting it to ‘Mikkel’ (as the inital state). 

See the Pen React useState by mikkel250 (@mikkel250) on CodePen.

 

You would use a new useState hook for each property you want to set or change, much like this.setState is called for each property that is being set or changed. 

Blog Comments

I don’t typically comment on posts, but as a long time reader I thought I’d drop in and wish you all the best during these troubling
times.

From all of us at Royal CBD, I hope you stay well with the COVID19 pandemic progressing at an alarming rate.

Justin Hamilton
Royal CBD

Hey there 🙂

Your wordpress site is very sleek – hope you don’t mind me asking what
theme you’re using? (and don’t mind if I steal it? :P)

I just launched my site –also built in wordpress like yours– but the theme slows (!) the site down quite a bit.

In case you have a minute, you can find it by searching
for “royal cbd” on Google (would appreciate any feedback) – it’s still in the works.

Keep up the good work– and hope you all take care of yourself
during the coronavirus scare!

Justin,

I’m happy to share. I used the HCode theme, although I also definitely noticed a performance hit using a theme as well.

Add a comment

*Please complete all fields correctly

Related Blogs