To pass parameters to a custom hook in React, you can define the custom hook to accept arguments just like any regular function. The custom hook can then use these arguments to perform some logic or return data. Here's how you can create and use a custom hook with parameters:

Let's create an example custom hook called useCustomHook that takes a parameter initialCount and returns the current count value and functions to increment and decrement the count:

import { useState } from 'react'; // Custom hook with parameters function useCustomHook(initialCount) { const [count, setCount] = useState(initialCount); const increment = () => { setCount((prevCount) => prevCount + 1); }; const decrement = () => { setCount((prevCount) => prevCount - 1); }; return { count, increment, decrement }; } export default useCustomHook;

Now, you can use this custom hook in your components by passing the initialCount as an argument:

import React from 'react'; import useCustomHook from './useCustomHook'; function MyComponent() { // Using the custom hook with parameter const { count, increment, decrement } = useCustomHook(0); return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); } export default MyComponent;

In this example, we call the useCustomHook inside the MyComponent and pass 0 as the initialCount. The hook returns the count value and functions increment and decrement. When the buttons are clicked, the count will be incremented or decremented accordingly.

You can pass any type of argument to your custom hook, such as numbers, strings, arrays, objects, or even other hooks. Custom hooks are a powerful way to encapsulate and reuse complex logic in your React components.

Have questions or queries?
Get in Touch