Clue Mediator

How to export multiple functions from a React hook

πŸ“…February 26, 2023
πŸ—ReactJS

In React, we often use hooks to manage stateful logic in our components. Sometimes, we may want to export multiple functions from a single hook, so that they can be used across multiple components.

To export multiple functions from a React Hook, we can simply define the functions as properties of an object, and then return that object from the hook.

Export multiple functions example:

import { useState } from 'react';

export function useCounter(initialCount) {
  const [count, setCount] = useState(initialCount);

  function increment() {
    setCount(count + 1);
  }

  function decrement() {
    setCount(count - 1);
  }

  return {
    count,
    increment,
    decrement
  };
}

In this example, we define a custom hook called useCounter, which takes an initial count as an argument and returns an object with three properties: count, increment, and decrement.

We can then use this hook in our components like so:

import { useCounter } from './useCounter';

function Counter() {
  const { count, increment, decrement } = useCounter(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

In this example, we import the useCounter hook and use it to manage stateful logic for a counter component. We can access the count, increment, and decrement functions by destructuring the object returned by the hook.

By exporting multiple functions from a single hook, we can create reusable stateful logic that can be easily shared across multiple components.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! πŸ™‚