An Introduction To The UseState Hook

Introduction

One of React's best features is that you can easily write JavaScript codes in your components before the return keyword. These dynamic scripts are displayed in your JSX template using curly braces. Take an example;

function App() {
  let text = "dynamic variables";

  return (
    <section className="app">
      <p>Let's talk about outputting {text} to the DOM.</p>
    </section>
  );
}

export default App;

Run the code

We can see from the example above that it is quite OK to output dynamic variables in your JSX template. Other than strings, we can output numbers and arrays but not objects or booleans.

Let's say you have two dynamic variables to use in your JSX template, and you want to return a new output when the user clicks a button. This is how you'd organize your code if you are unfamiliar with how the useState hook functions;

function App() {
  let name = "Stephanie";
  let color = "Blue";

  const handleChange = () => {
    name = "Bryan"
    color = "red"
    console.log(name)
    console.log(color)
  };

  return (
    <section className="app">
      <p>Hi I'm {name} and my favorite color is {color}</p>
      <button onClick={handleChange}>Click me </button>
    </section>
  );
}

export default App;

Run the code

If you click the button a hundred times, you'd never get to know Bryan's favorite color! Keep in mind that while the DOM was not changed, the console did receive the updated information. The changes will not trigger a re-render because React does not classify these variables as "reactive." For this reason, we'd require a state hook.

The UseState Hook

Think of the useState hook as the proper approach to define a variable in React that evolves when an action or event occurs.

There are three steps to using states in React;

  • Import the state from react
  • Define the state
  • Update the state

Syntax of the useState Hook

To implement the useState hook, you need to understand its syntax. useState utilizes array de-structuring, which takes two arguments: the variable and a setter function that can change the state; lastly, it sets the initial state value within the hook.

//Import the useState hook
import {useState} from 'react';

function App(){

//Define the state
  const [name, setName] = useState('Stephanie')
  const [color, setColor] = useState('Blue')

//Update the state
  const handleChange =()=>{
    setName('Bryan')
    setColor('red')
  }

  return(
    <section className = 'app'>
    <p>Hi I'm {name} and my favourite color is {color}</p>
    <button onClick ={handleChange}>Click me </button>
    </section>
  )
} 

export default App

Run this code

In the above example, notice that the setter function is used to alter the initial value of the state. That is all there is to using the useState hook. Once you get the hang of its syntax, using this hook becomes simpler. To wrap up, let's look at one more instance.

I'll build a basic counter app that contains a count variable and two buttons: one for increasing the count and one for decreasing it.

//import the state
import {useState} from 'react'

function App() {

//define the state
const [count, setCount] = useState(0);

//update the state
const increment = () =>{
  setCount(count + 1)
}
const decrement = () =>{
  setCount(count - 1)
}
  return (
    <section className="app">
      <button onClick ={decrement}>-</button>
      <p>{count}</p>
      <button onClick ={increment}>+</button>
    </section>
  );
}

export default App;

Run this code

In the above example, notice that the setter function modifies the count state and provides a new count value to the DOM for each button click. In conclusion, Keep these three things in mind while utilizing the useState hook:

Conclusion

  • Always define your states at the top of the functional component.
  • A functional component can contain as many states as you like.
  • The useState memory is local to that component.