DEV Community

Cover image for Custom Hooks in React: Use Cases and Significance
Hargun Singh
Hargun Singh

Posted on

Custom Hooks in React: Use Cases and Significance

Custom hooks in React are an excellent way to encapsulate reusable logic, manage state, and handle side effects in a way that keeps your code clean and maintainable. Here are some key use cases and the significance of creating custom hooks:

1. Reusing Logic Across Components

Example: Fetching data from an API.
You can create a custom hook like useFetch to encapsulate the logic for fetching data and handle loading, success, and error states. This logic can then be reused across multiple components.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        setData(data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error);
        setLoading(false);
      });
  }, [url]);

  return { data, loading, error };
};

export default useFetch;

Enter fullscreen mode Exit fullscreen mode

2. Managing Complex State Logic

Example: Managing form state
Custom hooks can be used to manage form state and validation logic in a reusable way.

import { useState } from 'react';

const useForm = (initialState) => {
  const [values, setValues] = useState(initialState);

  const handleChange = (event) => {
    const { name, value } = event.target;
    setValues({
      ...values,
      [name]: value,
    });
  };

  const resetForm = () => {
    setValues(initialState);
  };

  return [values, handleChange, resetForm];
};

export default useForm;

Enter fullscreen mode Exit fullscreen mode

3. Abstracting Side Effects

Example: Synchronizing with local storage.
You can create a custom hook to manage state that synchronizes with local storage.

import { useState, useEffect } from 'react';

const useLocalStorage = (key, initialValue) => {
  const [value, setValue] = useState(() => {
    const storedValue = localStorage.getItem(key);
    return storedValue ? JSON.parse(storedValue) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
};

export default useLocalStorage;

Enter fullscreen mode Exit fullscreen mode

Significance of Custom Hooks

1. Code Reusability
Custom hooks allow you to reuse logic across multiple components without duplicating code, promoting the DRY (Don't Repeat Yourself) principle.

2. Separation of Concerns
By moving logic out of components and into hooks, you can keep your component code cleaner and more focused on rendering, while the custom hook handles the logic.

3. Testability
Custom hooks can be tested independently from the components that use them, making it easier to write unit tests for complex logic.

3. Consistency
Using custom hooks ensures consistent behavior across different parts of your application, as the same logic is used wherever the hook is invoked.

Conclusion
Custom hooks in React are a powerful tool for creating reusable, maintainable, and testable code. They help you encapsulate complex logic, manage state and side effects efficiently, and promote best practices like separation of concerns and code reusability. By leveraging custom hooks, you can keep your components clean and focused on their primary purpose: rendering UI.

Top comments (0)