Home   reactjs  

List of all hooks in reactjs

React provides a variety of hooks that enable functional components to use state, lifecycle methods, and other React features without writing class components. Here is a list of all the built-in hooks in React:

Basic Hooks

  1. useState: Allows you to add state to functional components.

    const [state, setState] = useState(initialState);
  2. useEffect: Lets you perform side effects in functional components (e.g., data fetching, subscriptions).

    useEffect(() => {
      // side effect code
    }, [dependencies]);
  3. useContext: Allows you to subscribe to React context without introducing nested components.

    const value = useContext(MyContext);

Additional Hooks

  1. useReducer: An alternative to useState for managing more complex state logic.

    const [state, dispatch] = useReducer(reducer, initialState);
  2. useCallback: Returns a memoized callback function.

    const memoizedCallback = useCallback(() => {
      // callback code
    }, [dependencies]);
  3. useMemo: Returns a memoized value.

    const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  4. useRef: Returns a mutable ref object whose .current property is initialized to the passed argument.

    const refContainer = useRef(initialValue);
  5. useImperativeHandle: Customizes the instance value that is exposed when using ref in parent components.

    useImperativeHandle(ref, () => ({
      // exposed methods
    }), [dependencies]);
  6. useLayoutEffect: Similar to useEffect, but fires synchronously after all DOM mutations.

    useLayoutEffect(() => {
      // layout effect code
    }, [dependencies]);
  7. useDebugValue: Can be used to display a label for custom hooks in React DevTools.


Custom Hooks

React also allows you to create your own custom hooks. A custom hook is a function whose name starts with use and that can call other hooks.

Example of a Custom Hook

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch(url);
      const result = await response.json();

  }, [url]);

  return { data, loading };
Published on: Jul 04, 2024, 06:26 AM  


Add your comment