Understanding React Hooks: A Comprehensive Guide

Saturday 10 June 2023


React Hooks, introduced in React 16.8, are a powerful addition to the React library. They allow us to use state and other React features without writing a class component. Hooks bring to functional components the things we could only do in class components before. This includes working with the React local state, effects and context through useState, useEffect, and useContext hooks respectively.

What are React Hooks?

React Hooks are functions that let us hook into the React state and lifecycle features from function components. They do not work inside classes — they let you use React without classes. React provides a few built-in hooks like useState, useEffect, useContext, useReducer, useRef, etc.

useState Hook

The useState hook lets you add state to functional components. In classes, the state is always an object, and you can update a property in that object using the this.setState method. However, with the useState hook, the state doesn't have to be an object - it can be any type.

Here's an example of useState in action:


import React, { useState } from 'react';

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

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

export default Counter;

In this example, we declare a state variable called count, and set it to 0. We then render the count in the UI and increment it when the button is clicked.

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's an example of useEffect in action:


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

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

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

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

export default Example;

In this example, we set the document title to the current count when the component mounts and updates.

useContext Hook

The useContext hook is a built-in hook that allows you to use Context and gives you the current context value for that context as determined by the nearest matching Provider above the calling component in the tree.

Context provides a way to pass data through the component tree without having to pass props down manually at every level. In a typical React application, data is passed top-down (parent to child) via props. But for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application, Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

Here's an example of useContext in action:


import React, { useContext } from 'react';

// Create a Context
const NumberContext = React.createContext();

// It returns an object with 2 values: 
// { Provider, Consumer }

function Example() {
  // Use the Provider to make a value available to all 
  // children and grandchildren
  return (
    <NumberContext.Provider value={42}>
      <Display />
    </NumberContext.Provider>
  );
}

function Display() {
  // Use the Consumer to grab the value from context
  // Notice this component didn't get any props!

  const value = useContext(NumberContext);
  return <div>The answer is {value}.</div>;
}

export default Example;


In this example, we create a NumberContext with React.createContext(), then use the Provider in the Example component to make the number 42 available to all children and grandchildren of Example. Then, in the Display component, we use the useContext Hook to grab the value from the context, and display it.

Refer the below diagram to understand the flow of the above react hooks,


 In this diagram:

  • The "React Component" uses the "useState", "useEffect", and "useContext" hooks to manage its "State", perform "Side Effects", and access the "Context" respectively.
  • The "State" is updated using the "setCount" function, which triggers a re-render of the "React Component".
  • The "Side Effects" are performed, such as updating the document title, which also triggers a re-render of the "React Component".
  • The "Context" is accessed and its value is used, which again triggers a re-render of the "React Component".

No comments:

Post a Comment

 
About Contact Career Advertise Job Support Online Training Acardemic Projects Internship
Copyright © 2016. [ info ].
Design by Herdiansyah Hamzah. & Distributed by Free Blogger Templates
Creative Commons License