Why React Hooks?

It was all fine and good using state and props and classes in React. You want to build user interfaces in React? Start by creating the classes that extend the component.

Then React introduced React Hooks in React 16.8 version. Let us understand the main reason of introducing react hooks in short.

React Hooks is a new way of building user interfaces in React without having to create classes. You can have a simple JavaScript function, and you can use state and props features of React inside the JavaScript function using hooks.

As the name suggests, hooks allow you to hook into the specific features of React.

Example of stateful class written with React classes

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  state = {
    count: 10
  };
  updateCount = () => {
    const { count } = this.state;
    this.setState({
      count: count + 1
    });
  };
  render() {
    const { count } = this.state;
    return (
      <div className="App">
        <h1>React app with class {count}</h1>
        <button onClick={this.updateCount}>Update count</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

In the above component, on click of the button, the count state variable is updated and the value count variable is displayed on screen.

Example of hooks version of the above component (useState hook)

import React, { useState } from "react";
import ReactDOM from "react-dom";

const updateCount = (count, setCount) => () => {
  setCount(count + 1);
};

function App() {
  // initialize count to 10 and get the count and setCount function
  const [count, setCount] = useState(10);

  return (
    <div className="App">
      <h1>React app with hooks {count}</h1>
      <button onClick={updateCount(count, setCount)}>Update count</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

In the above component, we are using the useState hook. useState hooks accepts an argument, and returns the reference to that variable and a function to set the value.

useState is a Hook that lets you add React state to function components

So if you are initializing state variable count to 10 and updating it using setState function

...
state = {
count: 10
}

...
const { count } = this.state;
this.setState({
  count: count + 1
})

then above code changes to

const [count, setCount] = useState(0);

...
setCount(count + 1)