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. 

Add a comment

*Please complete all fields correctly

Related Blogs