Search

React Custom Hooks

  • Share this:

Custom hooks are a way to reuse stateful logic across multiple components. They allow you to extract stateful logic from a component and share it with other components. Custom hooks are just functions that follow a specific pattern: they start with the word `use` and may call other hooks inside them.

Here's an example of a custom hook that manages a simple form state:

import { useState } from 'react';

function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  function handleChange(event) {
    setValue(event.target.value);
  }

  return {
    value,
    onChange: handleChange
  };
}

function MyForm() {
  const name = useFormInput('');
  const email = useFormInput('');

  return (
    <form>
      <input type="text" {...name} />
      <input type="email" {...email} />
    </form>
  );
}

In this example, the `useFormInput` custom hook manages the state and event handling for a single input field. The `MyForm` component can use the `useFormInput` hook multiple times to create a reusable form input that can be used for different form fields.

Custom hooks are a powerful way to share logic between components and can help make your code more reusable and maintainable.

Tags:

About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.