React Higher order component with its example
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.