Published on

40+ React Hooks with Code

40+ React Hooks with Code

40+ React Hooks with Code

React Hooks

React Hooks are a set of functions introduced in React 16.8 that allow you to use state and other React features in functional components, as opposed to using class components. Hooks enable you to write cleaner, more concise code by allowing you to manage state and side effects without the need for classes.

Why Hooks required in React ?

Before Hooks, React components were often written using class syntax, which could lead to complex and hard-to-maintain code, especially when dealing with state management and lifecycle methods. React Hooks provide a more intuitive and functional approach to achieving the same functionality.

React built-in Hooks

React provides several built-in Hooks which can use directly and also can be used to compose them into custom hooks for a specific use case in your functionality. Follow official docs for more info.

  1. useState Hook: The useState hook allows you to add state to functional components. It returns a state value and a function to update that value. Here's an example:

  2. useEffect Hook: The useEffect hook is used for handling side effects in functional components. It runs after rendering and can be used for data fetching, subscriptions, and more. Here's an example:

  3. useContext Hook: The useContext hook is used to access context values in functional components. It provides a way to share data between components without having to pass props through every level. Here's an example:

  4. useReducer Hook: The useReducer hook is an alternative to useState for managing more complex state logic. It takes a reducer function and an initial state, returning the current state and a dispatch function to update the state. Here's an example:

  5. useCallback Hook: The useCallback hook is used to memoize functions, which can prevent unnecessary re-renders in child components. It takes a function and a dependency array and returns a memoized version of the function. Here's an example:

  6. useMemo Hook: The useMemo hook is used to memoize values, which can prevent unnecessary calculations in re-renders. It takes a function and a dependency array and returns a memoized value. Here's an example:

  7. useRef Hook: The useRef hook allows you to create a mutable reference that persists across renders. It's often used for accessing and interacting with DOM elements. Here's an example:

  8. useImperativeHandle Hook: The useImperativeHandle hook is used to customize the instance value that's exposed when using ref with forwardRef. It's typically used in conjunction with forwardRef to expose specific methods or properties of a child component to its parent. Here's an example:

  9. useLayoutEffect Hook: The useLayoutEffect hook is similar to useEffect, but it fires synchronously after all DOM mutations. It can be used for interactions with the DOM that require measurements or layout calculations. Example:

  10. useDebugValue Hook: The useDebugValue hook is used for displaying custom labels for custom hooks in React DevTools. It's primarily used for debugging and labeling custom hooks. Here's an example:

Migrating Class Components to Hooks:

If you're migrating from class components to functional components with hooks, here are some steps to follow:

  1. State Conversion: Identify where this.state is used and replace it with the useState hook. Convert lifecycle methods like componentDidMount and componentDidUpdate to useEffect.

  2. Event Handlers: Convert event handler methods like this.handleClick to standalone functions using the useState hook. Use the useCallback hook to prevent unnecessary re-renders.

  3. Context and Redux: Replace context and Redux usage with the useContext and useSelector hooks, respectively.

  4. Lifecycle Effects: Convert lifecycle methods that rely on component mounting or updates, like componentDidMount, to equivalent useEffect logic.

  5. Cleanup Effects: Convert componentWillUnmount and other cleanup logic to the cleanup function returned by the useEffect hook.

  6. Ref Conversion: Replace class-based this.refs with the useRef hook for accessing DOM elements.

By systematically converting class component features to functional components with hooks, you can ensure a smooth transition and leverage the benefits of the modern React development paradigm.

Custom Hooks in React

Rules to follow while Creating Custom Hooks:

When working with React Hooks, there are some important rules to follow:

  1. Only Call Hooks at the Top Level: Hooks must be called in the same order on every render, and they should not be called inside loops, conditions, or nested functions.

  2. Use Hooks Only in Functional Components: Hooks should only be used in functional components or other custom hooks, not in regular JavaScript functions or class components.

  3. Name Custom Hooks with "use": Custom hooks must be named with the “use” word followed by functionality(What that hooks do).

  4. Follow ESLint or Linter Rules: Make sure your code editor or linter is configured to detect violations of the Rules of Hooks.

By following these rules, you can ensure that your React code using hooks is consistent and avoids potential issues.

React Hooks have revolutionized the way we write React components, making them more modular, readable, and efficient. By mastering the use of hooks and understanding their nuances, you can build robust and maintainable React applications.

Creating Custom Hooks:

You can create your own custom hooks by combining built-in hooks to encapsulate specific behaviors or state management logic. Here's another example of a custom hook that manages dark mode for your application:

import { useState, useEffect } from "react";

function useDarkMode() {
  const [darkMode, setDarkMode] = useState(false);

  useEffect(() => {
    const body = document.body;
    if (darkMode) {
      body.classList.add("dark-mode");
    } else {
      body.classList.remove("dark-mode");
    }
  }, [darkMode]);

  return [darkMode, setDarkMode];
}

export default useDarkMode;

You can use the useDarkMode custom hook in your components like this:

import React from "react";
import useDarkMode from "./useDarkMode";

function App() {
  const [darkMode, setDarkMode] = useDarkMode();

  return (
    <div>
      <button onClick={() => setDarkMode(!darkMode)}>Toggle Dark Mode</button>
      <p>Dark Mode: {darkMode ? "On" : "Off"}</p>
    </div>
  );
}
export default App;

In this example, the useDarkMode hook encapsulates the logic for toggling a dark mode class on the body element. The custom hook returns the current darkMode state and a function to toggle it.

React Hooks offer a modern and more readable approach to working with state and side effects in React applications. They have become a fundamental part of building efficient and organized React components.

40+ Custom Hooks Example with Code

  1. useDebounce - Code Snippet
  2. useThroattle - Code Snippet
  3. useLocalStorage - Code Snippet
  4. useWindowSize - Code Snippet
  5. usePrevious - Code Snippet
  6. useIntersectionObserver - Code Snippet
  7. useNetworkState - Code Snippet
  8. useMediaQuery - Code Snippet
  9. useOrientation - Code Snippet
  10. useSessionStorage - Code Snippet
  11. usePreferredLanguage - Code Snippet
  12. useFetch - Code Snippet
  13. useContinousRetry - Code Snippet
  14. useVisibilityChange - Code Snippet
  15. useScript - Code Snippet
  16. useRenderInfo - Code Snippet
  17. useRenderCount - Code Snippet
  18. useRandomInterval - Code Snippet
  19. useCountdown - Code Snippet
  20. useQueue - Code Snippet
  21. useHover - Code Snippet
  22. useTimeout - Code Snippet
  23. useEventlistner - Code Snippet
  24. useKeypres - Code Snippet
  25. useSet - Code Snippet
  26. useCopyToClipboard - Code Snippet
  27. useBattery - Code Snippet
  28. useIdle - Code Snippet
  29. useToggle - Code Snippet
  30. useHistoryState - Code Snippet
  31. useGeolocation - Code Snippet
  32. usePageleave - Code Snippet
  33. useObjectState - Code Snippet
  34. useLogger - Code Snippet
  35. useFirstRender - Code Snippet
  36. useLongpress - Code Snippet
  37. useFavicon - Code Snippet
  38. useWindoScroll - Code Snippet
  39. useMeasure - Code Snippet
  40. useClickAway - Code Snippet
  41. useList - Code Snippet
  42. useCounter - Code Snippet
  43. useMouse - Code Snippet
  44. useOutsideClick - Code Snippet

Advanced Custom Hooks:

As you delve deeper into React Hooks, you can create custom hooks that encapsulate complex logic and provide specialized functionality. Here are some advanced custom hook ideas:

  1. usePagination: Build a hook that manages pagination state, including current page, items per page, and navigation controls.

  2. useWebSocket: Create a hook that handles WebSocket connections, sending and receiving messages, and managing real-time updates.

  3. useMediaQuery: Develop a hook that dynamically updates based on the viewport's media queries, allowing components to adapt to different screen sizes.

  4. useDebouncedSearch: Extend the debounce concept to create a hook that manages search functionality with a delay between user input and actual searches.

  5. useThrottleScroll: Build a hook that throttles the scroll event, preventing excessive updates when scrolling quickly.

Testing Custom Hooks:

Robust testing is essential to ensure the reliability and correctness of your custom hooks. You can use testing libraries like @testing-library/react-hooks to test hooks in isolation.

Here's an example of testing a custom hook using @testing-library/react-hooks:

import { renderHook, act } from "@testing-library/react-hooks";
import useCounter from "./useCounter";

test("useCounter hook increments count", () => {
  const { result } = renderHook(() => useCounter());

  expect(result.current.count).toBe(0);

  act(() => {
    result.current.increment();
  });

  expect(result.current.count).toBe(1);
});

By thoroughly testing your custom hooks, you ensure that they behave as expected and provide reliable functionality to your components.

Error Handling and Custom Hooks:

When creating custom hooks, consider how to handle errors and communicate them to consuming components. You can use the useReducer hook to manage error states and messages.

Here's an example of a custom error-handling hook:

import { useState, useReducer } from "react";

function useErrorHandler() {
  const [error, setError] = useState(null);

  const handleError = (message) => {
    setError(message);
  };

  const clearError = () => {
    setError(null);
  };

  return { error, handleError, clearError };
}

export default useErrorHandler;

By using this custom hook, you can easily manage and display errors in your components:

import React from "react";
import useErrorHandler from "./useErrorHandler";

function ErrorExample() {
  const { error, handleError, clearError } = useErrorHandler();

  const simulateError = () => {
    handleError("An error occurred.");
  };

  return (
    <div>
      <button onClick={simulateError}>Simulate Error</button>
      {error && <p>{error}</p>}
      <button onClick={clearError}>Clear Error</button>
    </div>
  );
}

Avoiding Performance Pitfalls:

While React Hooks offer many benefits, it's important to be aware of potential performance pitfalls. Here are a few tips to ensure your hooks are optimized:

  1. Memoize Callbacks: When passing callbacks as props, use useCallback to memoize them to prevent unnecessary re-renders of child components.

  2. Optimize Heavy Calculations: Use useMemo to memoize expensive calculations and prevent them from being recomputed on every render.

  3. Minimize State Updates: Be mindful of when to update state. Consider using the functional form of setState when the new state depends on the previous state.

  4. Use Dependencies Wisely: When using the dependency array in useEffect, include only the variables that are directly related to the effect. Avoid including unnecessary variables to prevent unintended effects.

  5. Debounce and Throttle: For performance-intensive tasks like API requests triggered by user input, consider using debounce or throttle techniques to avoid excessive requests.

Final Thoughts:

These built-in React hooks provide powerful tools for managing state, handling effects, optimizing performance, and interacting with the DOM. Understanding and effectively using these hooks can greatly enhance your React components and make your code more modular, maintainable, and efficient. Happy coding!