All React Hooks Explained With Examples

All React Hooks

Hey, Web Developers! In This Blog Post, We Will See All React Hooks And Explain Them With Clear Examples. React Hooks Are Functions That Let You Use State & Other React Features Without Writing Class.

Because Of This Feature Developers Can Build Web Applications That Are Cleaner & Manageable. We Will Walk Through Each Hook From The Basic Hooks Like ‘usesate’ And ‘useeffect’ To Advanced Hooks Like ‘usecontext & Usereducer.

So If You Are New To React Hook In React This Blog Post Will Help You Grasp The Concept Of Hooks And Guide You On How You Can Use Them To Create Advanced Frontend Web Applications.

Also Read: How To Set – Get Cookies With Express And MongoDB

What Are React Hooks: Brief Info

React Hooks Are Special Functions In React That Allows You To Handle Sate & Manage Other React Features Without Writing Class. There are various types of hooks like useState, UseEffect, UseContext with specific functionality.

All React Hooks Explained With Examples

Now I Hope You Understand What The Hooks Are But How Many Types Of Hooks Are There In React? According To The React There Are 10 Types Of Hooks In React That Are Considered To Be The Part Of Core React Js & They Are As Follows:

  1. UseState
  2. UseEffect
  3. UseContext
  4. UseReducer
  5. UseCallback
  6. UseMemo
  7. UseRef
  8. UseImperrativeHandle
  9. UseLayoutEffect
  10. UseDebugValue

So Now Let’s Get Into Each Hook Step By Step With Example:

Use State Hook:

import React, { useState } from 'react'
const mystate = () => {
  const [number, setNumber] = useState(0);
  const Increment = ()=>{
    setNumber(prenumber => prenumber+1);
  }
  const Decrement = ()=>{
    setNumber(prenumber => prenumber-1);
  }

  return (
    <>
    <div>{number}</div>
    <button onClick={Increment}>Increment</button>
    <button onClick={Decrement}>Decrement</button>
    </>
  )
}

export default mystate

In This Example, We Have Created Two Buttons One For Incrementing The Value & Another For Decreasing The Value Respectively. Each button has an onClick event handler to perform its respective function.

We Use The useState Hook To Create A State variable called number with an initial value of 0. This state variable will hold our current number. The useState hook also provides a function called setNumber to update the value of number.

When we click the increment button, it calls a function that increases the value of number using setNumber. Similarly, clicking the decrement button calls a function that decreases the value of number.

The great thing about this approach is that we can create multiple state variables for different numbers and update their values using their respective set functions, all declared in a similar manner.

UseEffect Hook In React:

  1. Purpose:useEffect allows performing side effects in functional components.
  2. Usage: It runs after every render and can perform actions like data fetching, subscriptions, or DOM manipulations.
  3. Example:
useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]);

Effect Definition: The useEffect hook takes a function as its first argument. This function contains the side effect we want to perform—in this case, updating the document’s title.

Dependency Array: The second argument to useEffect is an array of dependencies. The effect will only re-run if one of these dependencies changes. Here, the dependency is [count], which means the effect will re-run every time count changes.

Updating the Title: Inside the useEffect function, we set the document’s title to You clicked ${count} times. This ensures that whenever count changes, the document title is updated to reflect the new count.

UseContext Hook In React:

  1. Purpose:useContext provides a way to pass data through the component tree without having to pass props down manually at every level.
  2. Usage: It allows accessing values from the React context, useful for themes, user authentication, or any global data that needs to be accessed across components.
  3. Example:
const value = useContext(MyContext);

Importing useContext: First, make sure to import the useContext hook from React at the top of your file.

Creating Context: Assume we have a context called MyContext that we have created and provided a value for higher up in the component tree. This context might look something like this:

Accessing the Value: The useContext hook takes the context object as an argument and returns the current context value for that context. This allows any component in the tree to access the context value without having to pass props down manually.

UseReducer Hook In React:

  1. Purpose:useReducer is an alternative to useState for managing complex state logic in React.
  2. Usage: It accepts a reducer function and an initial state, and returns the current state and a dispatch method to trigger state transitions.
  3. Example:
import React, { useReducer } from 'react';
const initialState = { count: 0 };
const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>You clicked {state.count} times</p>
      <button onClick={() => dispatch({ type: 'increment' })}>
        Increment
      </button>
      <button onClick={() => dispatch({ type: 'decrement' })}>
        Decrement
      </button>
    </div>
  );
}

export default Counter;


Initial State: We define an initial state object { count: 0 } that will hold our count value.


Reducer Function: The reducer function handles state changes based on the action type. It uses a switch statement to decide how to update the state.

useReducer Hook: We use useReducer to create state and dispatch. state holds the current state, and dispatch is a function we use to send actions to the reducer.

Rendering: We render a paragraph displaying the current count and two buttons: The increment button calls dispatch with an action of type ‘increment’ to increase the count.
The decrement button calls dispatch with an action of type ‘decrement’ to decrease the count.

UseCallback Hook In React

  1. Purpose:useCallback memoizes a callback function, preventing unnecessary re-renders in child components.
  2. Usage: It’s used when passing callbacks to child components that rely on reference equality to optimize performance.
  3. Example:
const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);

Using useCallback: Inside your component, we use the useCallback hook to create a memoized version of the callback function doSomething. This function will only be recreated if the dependencies [a, b] change.

Callback Function: We add the callback function as the first argument to useCallback. This is the function we want to memoize.

Dependency Array: The dependency array [a, b] tells React when to recreate the memoized function. If either a or b changes, useCallback will return a new version of the function. If neither changes, the same function instance is returned.

UseMemo Hook In React

  1. Purpose:useMemo memoizes a value computed from a function, preventing expensive computations on every render.
  2. Usage: It’s useful for optimizing performance by storing the result of a computation and recalculating only when dependencies change.
  3. Example:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

UseRef Hook In React

  1. Purpose:useRef creates a mutable reference that persists across renders and doesn’t trigger re-renders when its value changes.
  2. Usage: It’s used to access DOM elements, store mutable values, or manage imperative actions.
  3. Example:
const inputEl = useRef(null);

Using useMemo: Inside your component, we use the useMemo hook to memoize the result of a potentially expensive computation. The useMemo hook takes two arguments. A function that performs the computation and a dependency array.

Computation Function: The function passed to useMemo is responsible for computing the value.

Dependency Array: The dependency array [a, b] ensures that the memoized value is recalculated only when either a or b changes.

UseImperativeHandle Hook In React

  1. Purpose:useImperativeHandle customizes the instance value that’s exposed to parent components when using ref.
  2. Usage: It allows a child component to expose certain functions or behaviors to its parent component.
  3. Example:
useImperativeHandle(ref, () => ({
  focus: () => {
    inputRef.current.focus();
  }
}));

Creating a Custom Component: We create a custom component that we want to expose imperative methods on. In this example, we are creating a component that wraps an input element and allows focusing on it imperatively.

Defining the Ref: We use forwardRef to forward a ref through our component to the input element inside it. This allows the parent component to directly interact with the input element.

Using useImperativeHandle: Inside the component, we use useImperativeHandle to define which methods should be exposed to the parent component. We pass the ref and a function that returns an object containing the methods we want to expose. In this case, we expose a focus method that calls the focus method on the input element.

UseLayoutEffect Hook In React

  1. Purpose:useLayoutEffect is similar to useEffect, but it runs synchronously after all DOM mutations.
  2. Usage: It’s used for tasks that require DOM measurements or need to manipulate the DOM immediately after the browser has rendered it.
  3. Example:
useLayoutEffect(() => {
  // DOM mutations
}, [dependencies]);

Using useLayoutEffect: Inside your component, we use the useLayoutEffect hook to perform side effects that involve DOM manipulations. The useLayoutEffect hook takes two arguments: a function and a dependency array.

Effect Function: The function passed to useLayoutEffect contains the code for the DOM manipulations. This code runs synchronously after all DOM mutations but before the browser repaints the screen.

Dependency Array: The dependency array [dependencies] ensures that the effect only runs when the specified dependencies change. This helps optimize the performance by running the effect only when necessary.

UseDebugValue Hook In React

  1. Purpose:useDebugValue adds a label to custom hooks for easier debugging in React DevTools.
  2. Usage: It’s used to display a label for custom hooks and provide additional information when inspecting hooks in development tools.
  3. Example:
useDebugValue(isOnline ? 'Online' : 'Offline');

Using useDebugValue: Inside your custom hook or component, we use the useDebugValue hook to provide a readable label for our state. In this case, we are checking if the user is online or offline and labeling the state accordingly.

Conditional Label: The useDebugValue hook takes a value that will be displayed in React DevTools. Here, we use a ternary operator to check the isOnline state. If isOnline is true, the label will be ‘Online’. If isOnline is false, the label will be ‘Offline’.


Last Updated: August 10, 2024

By JSM Hemant

About Author

Hello, Myself Hemant. I Am Web Developer & Likes To Create Awesome Projects By Using MERN, Java, Python, C++. In This Website You Will Get Cool Projects Made With Above Technologies With Full Source Code. You Can Also Follow This Website On Author Social Media:

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories

Recent Posts