DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for React Hooks For Beginners : useState
Lukas Mills
Lukas Mills

Posted on • Updated 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!

Oldest comments (0)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›