Mastering React Hooks: Custom Hooks

Mastering React Hooks: Custom Hooks

React Custom Hooks provide a powerful way to extract and reuse logic and stateful behavior from components, reducing the amount of boilerplate code in your application. Custom Hooks are simply JavaScript functions that follow specific naming conventions and rules, allowing them to work as React Hooks.

Custom Hooks can be used to encapsulate complex logic into a single function and reuse that function across multiple components. They follow naming conventions, starting with the prefix use, and can use other React Hooks like useState, useEffect, and useContext, as well as other Custom Hooks, allowing you to compose Hooks together to create complex functionality.

In short, Custom Hooks in React allow you to extract common functionality into reusable, composable functions that can be easily shared and composed together.

When to Use Custom Hooks?

You can use Custom Hooks in any situation where you want to reuse functionality across multiple components. Custom Hooks are particularly useful for situations where you have complex stateful logic that needs to be reused across multiple components.

For example, if you have a component that fetches data from an API and then displays that data, you can extract the data fetching logic into a Custom Hook and reuse it across multiple components. This can greatly simplify your code and make it easier to maintain.

How to Create Custom Hooks?

Creating Custom Hooks in React is simple. You can create a Custom Hook by defining a function that encapsulates your logic and returns a value. The function should start with the prefix use and should follow the same rules as other Hooks in React.

Here is an example of a Custom Hook that returns a boolean value based on the current window size:

import { useState, useEffect } from 'react';

function useWindowSize() {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth <= 768);
    handleResize();
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return isMobile;
}

In this example, the useWindowSize function encapsulates the logic for checking the window size and returns a boolean value indicating whether the window is mobile size or not. The Hook uses the useState and useEffect Hooks to manage the state of the isMobile variable and listen for window size changes.

How to Use Custom Hooks?

Using Custom Hooks in React is just like using any other Hook. You simply call the Custom Hook function inside a component and use the returned value in your component.

Here is an example of using the useWindowSize Custom Hook in a React component:

import { useWindowSize } from './useWindowSize';

function MyComponent() {
  const isMobile = useWindowSize();

  return (
    <div>
      {isMobile ? (
        <h1>Mobile View</h1>
      ) : (
        <h1>Desktop View</h1>
      )}
    </div>
  );
}

In this example, the useWindowSize Custom Hook is used inside the MyComponent component to determine whether the window is mobile size or not. The isMobile value returned by the Hook is then used to conditionally render different content in the component.

Advanced Examples

Custom Hooks can be used to create more complex functionality as well. Here are some advanced examples of Custom Hooks:

UseForm Hook

The useForm Hook is a common Custom Hook that simplifies form handling in React. The Hook encapsulates the logic for managing form state and validation.

import { useState } from 'react';

function useForm(initialValues, onSubmit) {
  const [values, setValues] = useState(initialValues);
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});

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

  const handleBlur = (event) => {
    const { name } = event.target;
    setTouched({ ...touched, [name]: true });
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    const formErrors = validate(values);
    setErrors(formErrors);
    onSubmit(values);
  };

  const validate = (values) => {
    const errors = {};
    // perform validation logic
    return errors;
  };

  return {
    values,
    errors,
    touched,
    handleChange,
    handleBlur,
    handleSubmit,
  };
}

In this example, the useForm Hook encapsulates the logic for managing form state and validation. The Hook returns an object with properties that can be used in a form component to manage the form state.

UseModal Hook

The useModal Hook is another common Custom Hook that simplifies creating and managing modal windows in React.

import { useState } from 'react';

function useModal() {
  const [isOpen, setIsOpen] = useState(false);

  const openModal = () => setIsOpen(true);
  const closeModal = () => setIsOpen(false);

  return { isOpen, openModal, closeModal };
}

In this example, the useModal Hook encapsulates the logic for managing modal windows. The Hook returns an object with properties that can be used in a component to manage the modal state.

Conclusion

We have covered the basics of Custom Hooks in this article, including how to create them and use them in a React component. We also explored some advanced examples of Custom Hooks, such as the useForm and useModal Hooks.

By utilizing Custom Hooks in your React projects, you can create more composable and extendable code that is easier to work with and maintain. So next time you find yourself repeating logic or stateful behavior across multiple components, consider creating a Custom Hook to simplify your code and save time in the long run.