DEV Community

Jimmy Parrish
Jimmy Parrish

Posted on

How to {useState} in React

What is state? In React, components have a built-in state object. It’s where you store dynamic property values. Meaning, it is able to change as the user interacts with your application. When this object changes, the component re-renders. For example, let’s say you’re on a pet adoption application. You see a picture of a cute pup and would like to see additional info that pertains to that pup. Underneath the pic, there is a <button> that says “About Me”.

Image description

You click the <button>and information about the pup is displayed on the page.

Image description

You click again, the information disappears. In this example, state is set to a Boolean (false). When the user clicks the <button>, state changes to true, and shows the information wanted. Let’s break this down to see how this is done.

Import {useState}

At the top of the component that will hold your state, import the {useState} Hook.

Image description

Initialize {useState}

We initialize {useState} by calling it in our function component. {useState) accepts an initial state and returns two values
*The current state(false)
*A function that updates the state

Image description

At this point, we can now use our state variable in our component. In this example, I create a handleDogClick() function that uses the setState function(the function that updates the state)to toggle between showDogDetails(false) and !showDogDetails(true).

Image description

in the <button> element, I then add an onClick event and pass the {handleDogClick} function. This triggers the function to change state.

Image description

At this point, I need display the dog details when the state variable(showDogDetails) = true, and remove the details when showDogDetails = false. Under the <button>, I'm going to write a ternary operater (condition ? expression if true : expression if false). My condition will be the state variable showDogDetails. If showDogDetails = true, I want the show the dog's details. If false, I don't want to show anything. It will look like this.

Image description

That's all there is to it. I mean, it can definitely become more complicated than that, but this is just simple example.

Using state is a crucial element in creating dynamic React applications. It provides us with a way to maintain and update information within a component without requiring its parent to somehow send updated information. Hopefully, this helps in some capacity in your coding journey.

Resource:
“useState - React Hooks: W3Schools." | W3Schools,
(https://www.w3schools.com/react/react_usestate.asp)

Top comments (0)