DEV Community

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

Posted on • Edited on

2 2

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!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay