DEV Community

CluelessTurtle
CluelessTurtle

Posted on • Updated on

How To Use The State React Hook

Why use state?

One of the coolest things to see as a software developer is your web app being interactive with your users. This is the main reason why I love using state in my code. It updates and changes your web app in real time and gives your website that liveliness that users will appreciate. Best of all, once you get a good grasp on how state works it is not at all complicated to impletment into your code.

What exactly is state?

State is data that is dynamic.This means that when the user interactes with your app the data is changing and updating during the components life. When state changes it re-renders the component with new data which then is either displayed on the DOM or held.

How do you use state?

Using state is simple and only requires three steps.

  1. Import State
  2. Initilize State
  3. Use State in our component
  4. Setting and updating State

Importing State

Within each component we have to import state. We only need to do this once per component. For example, we have a component that has a button and when the user clicks that button the user either logs in or out.

import React from "react";

function App() {

  function handleClick() {
   console.log("I was clicked!")
 }

  return (
   <div>
   <button onClick={handleClick}> Log In! </button>
   <div>
 }
Enter fullscreen mode Exit fullscreen mode

In the code above all we have is a button logs on the console "I was clicked!". In this example, it does not change the text inside the button at all leaving the user confused. The first step to tackling this problem is importing the useState hook.

import React, { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

This is how we tell the code to react and create a new state for us to work with. Next we are going to have to initalize state and provide it a starting value.

Initilize State

Now that react knows we want to create a state in this component. We have to initilize the start. In other words we have to give it a name and an initial value.

function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
}
Enter fullscreen mode Exit fullscreen mode

In the code above we are constructing two variables from state which are isLoggedIn and setIsLoggedIn. isLoggedIn is a reference to the current state in our component in our case the boolean value false. The setIsLoggedIn is a function that we can use to update the state at any point in our component. Lastly we equal everything to useState to tell react where we are conctructing these variables from and put in between the parenthesis the starting value of our state.

Using State in our component.

Now we have our state created and initalized. Let's impliment this state into our component and talk about what we want to do in this component.

  1. when the user comes to the website they are logged out and button text says log in
  2. upon clicking the button the users log in
  3. while user is logged in the button says log out
  4. upon clicking the button again the user logs out

The idea here is while the state is false the user is logged out and while the state is true the user is logged in. The best way to go about this is through conditional rendering in our JSX.

import React, { useState } from "react";

function App() {

  const [isLoggedIn, setIsLoggedIn] = useState(false)

  function handleClick() {
   console.log("I was clicked!")
 }

  return (
   <div>
   <button onClick={handleClick}> {isLoggedIn ? "Log Out" : "Log In"} 
   </button>
   <div>
 }
Enter fullscreen mode Exit fullscreen mode

Through the conditional operator when isLoggedIn is True the buttons text will display log out and when it is false it will display log in. So far so good we have one more step to go through before we are done with this component.

Setting and Updating State

So with what we have so far the user still does not see the change in the text of the button instead all that happens is "I was clicked" gets console logged. We still also have to figure out how we are going to set state to its opposite. Lucky for us there is an operator for this.

import React, { useState } from "react";

function App() {

  const [isLoggedIn, setIsLoggedIn] = useState(false)

  function handleClick() {
   setIsLoggedIn((isLoggedIn) => !isLoggedIn)
 }

  return (
   <div>
   <button onClick={handleClick}> {isLoggedIn ? "Log Out" : "Log In"} 
   </button>
   <div>
 }
Enter fullscreen mode Exit fullscreen mode

In our handleClick callback function we use setIsLoggedIn function to update our state. Remember that whenever we change our state it re-renders the whole component. In this case, now our conditional operator in the jsx will be re-rendered to show the current logged state of our user. Inside the setIsLoggedIn function we have a callback function that takes the current state in our component and we use the bang(!) operator to switch the state to its opposite boolean value. There we go, we just made a working log in button with state

Conclusion

The useState hook is a very powerful tool in react that every developer should have handy. Think about the endless possibilities that as developers this gives us! Not to mention this also makes our apps more interactive with the users which is an important goal.

Top comments (0)