0 votes
in React Hooks by
Provide an example of any simple Custom React Hook. Why do we need Custom Hooks?

1 Answer

0 votes
by

A Custom Hook is a stateful function that uses other react built-in hooks (e.g. useState, useCallback etc.) that can wrap around the stateful logic that you wanted to gather in one place and avoid copying and pasting the same logic in multiple components.

Consider the increment/decriment custom hook:

const useCounter = () => {

  const [counter, setCounter] = useState(0);

  return {

    counter, // counter value

    increment: () => setCounter(counter + 1), // function 1

    decrement: () => setCounter(counter - 1) // function 2

  };

};

and then in your component you can use it as follows:

const Component = () => {

  const { counter, increment, decrement } = useCounter();

  return (

    <div>

      <span onClick={decrement}>-</span>

      <span style={{ padding: "10px" }}>{counter}</span>

      <span onClick={increment}>+</span>

    </div>

  );

}

Related questions

0 votes
0 votes
asked May 30, 2023 in React Hooks by Robindeniel
0 votes
asked Dec 17, 2023 in Google Cloud by AdilsonLima
...