React Hooks

With the introduction of hooks, it is now possible for functions to have state and use other logics that formally belonged to class components.

There are many hooks in React but for now, we will be looking into the useState hook and discuss others as we progress. useState() as the name suggests allows us to use a state in our functions.

Usage of Hook

useState() takes an argument which is the initial value of the state. The initial value can be a string, a number, null, or an array.

To implement useState(), we must import it first:

import React, { useState } from "react";

function SayName() {
  const [name, setName] = useState("Jane");
  return <h1> My name is {name} </h1>;
}

Result:

In the example above, we defined a state with a variable of name and an initial value of ‘Jane’ and a function setName that will be used to change the initial value of the state, The square brackets wrapping name and setName is an ES6 method called array destructuring that assigns a name to ‘Jane’ and setName to a function capable of changing the initial state. The above code renders a <h1> tag of ‘My name is Jane’.

We can change the state thus:

import React, { useState } from "react";

function SayName() {
  const [name, setName] = useState("Jane");
  const changeName = () => {
    setName("Doe");
  };
  return (
    <div>
      <h1> My name is {name} </h1>
      <button onClick={changeName}>Change name</button>
    </div>
  );
}

export default SayName;

The above example uses the setName function to change the state of the component from ‘Jane’ to ‘Doe’.

When should I use the Hook

Previously in React when you needed to store data in a state, we use a class component, but now you can create a state using the useState hook. This does not mean that class components has now been rendered useless, class components are still very useful as they contain many useful lifecycle methods(discussed later) you can plug-in to during the lifecycle of a component. In fact, React are not planning to remove class components anytime soon.

Putting it together

Let’s go through another example where we will update the state after an event handler function is triggered.

App.js:

import React, { useState } from "react";

const App = () => {
  const [count, setCount] = useState(0);
  const increase = () => {
     setCount(count + 1)
  };
  const decrease = () => {
   setCount(count - 1)
  };
  return (
    <div>
      <button onClick={increase}>+</button>
      <p>Current count: {count}</p>
      <button onClick={decrease}>-</button>
    </div>
  );
};

export default App;

We created two buttons: + and -, the event handler increase() or decrease(), increases or decreases the state variable on clicking the respective buttons. The setCount function enable us to edit the state. The state variable, count was initialized at 0.

Result: