DEV Community

Cover image for React Hooks For Beginners : useState
Lukas Mills
Lukas Mills

Posted on • Edited on

React Hooks For Beginners : useState

The useState hook allows us to create state variables in a React function component, also useState allows us to access and update certain values in our components over time. Finally, whenever we do create our useState hook we must give it a default value, and this can be any data type.

Before we start working with useState we must import it from React.

Example:

import { useState } from 'react'
Enter fullscreen mode Exit fullscreen mode

And just like that you have access to all of the wonderful things that useState has to offer. But now what if we wanted to use our useState hook in a real world scenario?

Example:

import { useState } from 'react'

function favoriteAvengers() {

const [avenger, setAvenger] = useState('Spider-man')

// avenger: a variable that stores the current value of our favorite avenger 'Spider-man'
// setAvenger: allows us to update or change the value of our avenger variable over time.
// useState('Spider-man'): is our default value of our variable 'avenger'
Enter fullscreen mode Exit fullscreen mode

Now let's add a button that changes our state to a different avenger when it's clicked:

import { useState } from 'react'

function favoriteAvengers() {

const [avenger, setAvenger] = useState('Spider-man')

return (

<h1>My favorite Avenger is {avenger}!</h1>

<button
type ='button'
onClick={() => setAvenger('Thor')}
>Change Avenger</button>
)}
Enter fullscreen mode Exit fullscreen mode

Now this is just the tip of the iceberg on what you can do with state, but this gives you a basic and fundamental understanding of how useState works!

Top comments (0)