Understanding React Hooks: useState and useEffect guide for beginners

Understanding React Hooks: useState and useEffect guide for beginners

Published by Ram Karan on June 2023

React Hooks are a revolutionary feature that simplify your code, making it easy to read, maintain, test in isolation and re-use in your projects. In this article, we will dive deep into understanding the useState and useEffect hooks in React.

Understanding React Hooks: useState and useEffect

Introduction to Hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

useState Hook

The useState is a Hook (we'll talk about what this means in a moment) that allows you to add React state to function components. Here is an example:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In the above example, the useState hook takes the initial state as a parameter (0 in this case) and returns an array containing the current state and a function to update it. We can then use the setCount function to update the state.

useEffect Hook

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API. Here is an example:

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

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

  useEffect(() => {
    document.title = `You clicked count times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Author:

author

Ram Karan

MERN Stack Developer