Introduction React Hooks

Introduction React Hooks

React Hooks are a way to use state and other React features in functional components. They were introduced in React 16.8 as an alternative to class-based components and have since become a popular way to manage state and side effects in React applications.

UseState:

This hook allows you to add state to your functional component. It returns an array with two values: the current state and a function to update it.

import React, { useState } from ‘react’;

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

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

useEffect:

This hook allows you to synchronize a component with an external system. It is used for side effects such as fetching data, setting up a subscription, and manually changing the DOM.

import React, { useState, useEffect } from ‘react’;

function Example() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch(‘https://my-api.com/data’)
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <>
      {data.map(item => (
        <p key={item.id}>{item.name}</p>
      ))}
    </>
  );
}

 

useContext:

This hook allows you to access the value of a context. It makes it easy to share data between components without having to pass props down manually through every level of the component tree.

import React, { useContext } from ‘react’;

const MyContext = React.createContext();

function Example() {
  const value = useContext(MyContext);

  return <p>{value}</p>;
}

useRef:

This hook allows you to create a reference to a DOM node or a component instance. This can be useful for storing information that doesn’t need to trigger a re-render when it changes.

import React, { useRef } from ‘react’;

 

function Example() {
  const inputRef = useRef(null);

 

  function handleClick() {
    inputRef.current.focus();
  }

 

  return (
    <>
      <input ref={inputRef} type=“text” />
      <button onClick={handleClick}>Focus the input</button>
    </>
  );
}

useMemo

This hook allows you to memoize a value. It will only recompute the memoized value when one of the dependencies has changed. This can help improve the performance of your application by avoiding unnecessary re-renders.

import React, { useMemo } from ‘react’;

function Example({ data }) {
  const memoizedValue = useMemo(() => {
    // Expensive computation
    return data.filter(item => item.active).length;
  }, [data]);

  return <p>{memoizedValue}</p>;

useReducer

useReducer is a React hook that allows you to manage state in a predictable way using a reducer function. It is similar to the reduce method in JavaScript, and it is often used for more complex state management. It takes two arguments: the reducer function and the initial state. The reducer function takes the current state and an action as arguments and returns the next state. Here’s an example of how you might use useReducer to manage a simple counter:

 
import React, { useReducer } from ‘react’;

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 Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: ‘increment’ })}>Increment</button>
      <button onClick={() => dispatch({ type: ‘decrement’ })}>Decrement</button>
    </>
  );
}

Other Popular React Hooks:

 useTransition, useDeferredValue, useId, useSyncExternalStore and useInsertionEffect are not official hooks from the React team. These are  hooks created by other developers or in development but not officially released by React Team yet.

 

useTransition: This hook is often used for handling transitions and animations in a component. It allows the developer to control the state of the animation, such as its play state, delay, and duration. It returns an object with the current state of the transition and a start method that can be used to trigger the transition.

 

useDeferredValue: This hook is often used for deferring the calculation of a value until the next render. It allows the developer to optimize performance by avoiding unnecessary calculations. It returns a value that will be updated in the next render.

 

useId: This hook is often used for generating unique ids for elements in a component. It allows the developer to ensure that each element has a unique id, which is necessary for accessibility and other purposes.

 

useSyncExternalStore: This hook is often used for syncing data between a component and an external store. It allows the developer to keep the component in sync with the store and update the component when the store changes.

 

useInsertionEffect: This hook is often used for handling side effects when an element is inserted into the DOM. It allows the developer to perform an action, such as setting focus or adding an event listener, when an element is added to the DOM.

 

Please note that these hooks may not have been officially released by the React team yet and could be in development or in experimental phase. Also, it’s good to check the React documentation for the most recent hooks and updates.

Tags :

Coding

Share :