Using React Hooks - useState and useEffect

With the release of Hooks in React 16.8, it is now possible to store state in a function. We can add react features like useState and useEffect into the function directly without needing to create class.


The useState hook adds state to the functional components. useState hook allows you to declare one state variable at a time.

import React, { useState } from 'react';

function Counter() {
  //Declare the "counter" state variable
  const [counter, setCounter] = useState(0);

  return (
        <p>Clicked {counter} times</p>

        //increment the counter by 1 on every click
        <button onClick={() => setCounter(counter + 1)}>Click here</button>


The useEffect allows to manage side effects in a functional component. Some of the examples are fetching external data using api, manipulating DOM in react. It is similar to componentDidMount and componentDidUpdate from class component.

import React, { useState, useEffect } from 'react';

function LoadProducts() {
  //Declare the "products" state variable
  const [products, setProducts] = useState([]);

  useEffect(() => {
      .then(response => response.json())
      .then(data => {
        setProducts(data); // add product list to the state array.
  }, []); 

  return (
        {, index) => (
            <div key={index}>