DEV Community

Tanzeel Ur Rehman
Tanzeel Ur Rehman

Posted on

Custom hooks in React.js

In React, a hook is a function that allows you to "hook into" React features from a function component. There are several built-in hooks provided by React, such as useState and useEffect.

Custom hooks are a way for you to extract component logic into reusable functions. They allow you to abstract logic that can be shared between multiple components into a single, reusable function.

Here is an example of a custom hook that manages a form input state:

import { useState } from 'react';

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

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

  return {
    value,
    onChange: handleChange
  };
}

export default useInput;

Enter fullscreen mode Exit fullscreen mode

This custom hook can be used in a form component like this:

import React from 'react';
import useInput from './useInput';

function Form() {
  const email = useInput('');
  const password = useInput('');

  return (
    <form>
      <input type="email" {...email} />
      <input type="password" {...password} />
      <button type="submit">Submit</button>
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

The useInput hook manages the state for the email and password inputs, and the handleChange function updates the value of the input when the user types in it. The ...email and ...password syntax is the object spread operator, which spreads the properties of the email and password objects as props for the corresponding input elements.

Top comments (0)