Blog Highlights

Explore my latest thoughts, insights, and innovations in technology, AI, development, and security. Dive into comprehensive guides and analyses.

Back to all posts

Custom React Hooks

June 2, 2023 by Rakesh Udutha Read Time: 1 min readReact

A Custom Hook is a stateful function that uses other react build-in hooks (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/decrement 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>
  );
}