Useful hooks in ReactJs

reactjs hooks

ReactJs is a JavaScript library for building user interfaces, and it provides a number of “hooks” that allow developers to add specific functionality to their components. Here are some of the most commonly used hooks in React:

useState:

A hook in ReactJs that allows you to add state to your functional components.

State is a way of keeping track of data that can change within your component, and it’s a powerful tool for managing complex user interfaces.

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>
  );
}

useEffect:

A hook in ReactJs that allows you to perform side effects (such as data fetching or updating the DOM) in your functional components.

It’s a way to add behavior to your components that is triggered by changes in their props or state.

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

function Example() {
  // Declare a state variable called "count" and initialize it to 0
  const [count, setCount] = useState(0);

  // Use the useEffect hook to perform a side effect whenever count changes
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]); // Only re-run the effect if count changes

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

useContext:

A hook in React that allows you to access data stored in a context (created with the React.createContext method) from your functional components.

It provides a way to share data between components without having to pass props down through every level of the component tree.

By using useContext, we can access the value stored in the context from within the component, and use it to update the component’s state or behavior.

This makes it easier to manage data that is shared across multiple components, without having to pass props down through every level of the component tree.

import React, { createContext, useContext } from 'react';

// Create a context with an initial value
const ThemeContext = createContext('light');

function Example() {
  // Use the useContext hook to access the value from the context
  const theme = useContext(ThemeContext);

  return (
    <div className={`theme-${theme}`}>
      <p>The current theme is {theme}</p>
    </div>
  );
}

useReducer:

A hook in React that allows you to manage state in a way that is similar to using a reducer function in Redux.

It provides a way to manage complex state transitions in your components by using a pure function to describe how the state should be updated.

import React, { useReducer } from 'react';

// Define the reducer function
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Example() {
  // Use the useReducer hook to manage state with the reducer function
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
}

The useReducer hook takes two arguments: the reducer function, and an initial state.

It returns an array with two values: the current state, and a dispatch function that you can use to trigger state updates by dispatching actions.

In this case, we’re using the dispatch function to trigger updates to the state whenever the + or – buttons are clicked.

useMemo:

A hook in React that allows you to optimize your component’s performance by memoizing a value.

It takes a function that returns a value, and an array of dependencies, and returns a memoized value that is only recalculated if one of its dependencies has changed.

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

function Example() {
  // Use the useState hook to manage a count state
  const [count, setCount] = useState(0);

  // Use the useMemo hook to memoize a value
  const expensiveComputation = useMemo(() => {
    let sum = 0;
    for (let i = 0; i < count; i++) {
      sum += i;
    }
    return sum;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
      <p>Expensive computation: {expensiveComputation}</p>
    </div>
  );
}

useMemo hook takes two arguments: a function that returns the value to be memoized, and an array of dependencies. In this case, the function returns the result of an expensive computation that depends on the count state, and the array of dependencies is [count] so that the value will be recalculated only if the count changes.

useCallback:

A hook in React that allows you to memoize a callback function.

It takes a function and an array of dependencies, and returns a memoized callback that is only re-created if one of its dependencies has changed.

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

function Example() {
  // Use the useState hook to manage a count state
  const [count, setCount] = useState(0);

  // Use the useCallback hook to memoize a callback
  const handleClick = useCallback(() => {
    console.log('You clicked', count);
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

By using useCallback, you can avoid creating a new function on every render, which can improve the performance of your component by reducing the number of unnecessary object allocations. The memoized callback is stored in memory, and is only re-created if one of its dependencies has changed, making useCallback an effective way to optimize your components for performance.

Read More:
https://scribblersden.com/api-testing-using-postman/

Thank You

Related Post

One thought on “Useful hooks in ReactJs

Leave a Reply

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