How to create a custom Hook in React?

To create a custom Hook in React, you can follow these steps:

  1. Create a new JavaScript file for your custom Hook, for example "useCustomHook.js".
  2. Import the necessary React dependencies at the top of the file:
import { useState, useEffect } from 'react';
  1. Define and export your custom Hook function:
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 }; };
  1. In your React components, import and use your custom Hook:
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;
  1. Your custom Hook is now ready to use in your React components. You can reuse this Hook in multiple components to encapsulate and reuse logic across your application.