React Higher order component with its example

Atiq ur rehman
1 min readMar 14, 2023

--

In React Hooks, a Higher Order Component can be replaced with a Higher Order Function (HOF) that returns a custom Hook.

Here’s an example of a Higher Order Function that returns a custom Hook to handle form input:

import { useState } from 'react';

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

const handleChange = (e) => {
setValue(e.target.value);
};

return {
value,
onChange: handleChange,
};
};

export default useFormInput;

In this example, useFormInput is a Higher Order Function that takes an initial value and returns a custom Hook that manages the input state and provides an onChange function to update the value.

Here’s an example of how this custom Hook can be used in a component:

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

const MyForm = () => {
const nameInput = useFormInput('');
const emailInput = useFormInput('');

const handleSubmit = (e) => {
e.preventDefault();
console.log(`Name: ${nameInput.value}, Email: ${emailInput.value}`);
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" {...nameInput} />
</label>
<label>
Email:
<input type="email" {...emailInput} />
</label>
<button type="submit">Submit</button>
</form>
);
};

export default MyForm;

In this example, useFormInput is called twice to create two custom Hooks, nameInput and emailInput, which are used to manage the input state of the Name and Email fields respectively.

The spread operator ...nameInput and ...emailInput are used to pass the value and onChange props to the respective input fields. This allows the component to reuse the useFormInput Hook to manage input state without the need to write repetitive code.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Atiq ur rehman
Atiq ur rehman

No responses yet

Write a response