React Hooks: useState - Basic Implementation

This article outlines the basic implementation of useState - one of the many React Hooks.

Step - 1 -> import useState from React.

import React, { useState } from 'react';

Step - 2 -> Declare the state variable for the component

const [name, setName] = useState('');  //destructuring syntax

The useState statement above sets the initial value of name as spaces.

What's useState ?

It returns a pair of values. The first is the state value and the second is the function that we call to update the state also called as updater function.

Step - 3 -> Below is an example where we track the state as name changes. Use the setName function to set the value of name.

import React from 'react'

function Greeting({initialName}) {
  const [name, setName] = React.useState(initialName)

  function handleChange(event) {
    setName(event.target.value)

  }

  return (
    <div>
      <form>
        <label htmlFor="name">Name: </label>
        <input value={name} onChange={handleChange} id="name" />
      </form>
      {name ? <strong>Hello {name}</strong>  : 'Please type your name'}
    </div>
  )
}

function App() {
  return <Greeting initialName="LaN" />
}

export default App

Output of the program:

image.png

As we enter our name the input handleChange function is called to update the name.

Calling setName means we are telling react to re-render our component. The value we get back is the value we used while calling the setName with.

Thank you for reading the basic implementation of useState. Thanks to Kent C. Dodds' React Hooks course.