To create a custom Hook in React, you can follow these steps:
import { useState, useEffect } from 'react';
export const useCustomHook = () => {
const [state, setState] = useState(initialState);
useEffect(() => {
// Add any side effects or logic here
return () => {
// Clean up code if needed
};
}, []);
const updateState = (newValue) => {
setState(newValue);
};
return { state, updateState };
};
import React from 'react';
import { useCustomHook } from './useCustomHook';
const Component = () => {
const { state, updateState } = useCustomHook();
return (
<div>
<p>Value: {state}</p>
<button onClick={() => updateState('New Value')}>Update Value</button>
</div>
);
};
export default Component;