Building Custom Hooks in React

Expert-Level Explanation

Custom hooks in React are functions that start with use and can call other hooks. They allow you to extract component logic into reusable functions. A custom hook allows you to encapsulate stateful logic and share it across multiple components. By building custom hooks, you can simplify your components and keep them focused and manageable.

Creative Explanation

Imagine custom hooks as personalised toolkits. Each toolkit is tailored for a specific task or project, containing a set of tools (state, effects, and context) that are precisely arranged for efficiency. These toolkits can be shared and used in different projects (components) where similar functionality is needed.

Practical Explanation with Code

Example of creating a custom hook:

import { useState, useEffect } from 'react';

function useCustomCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);

  useEffect(() => {
    // Side effects or additional logic
  }, [count]);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return { count, increment, decrement };
}

// Usage in a component
function CounterComponent() {
  const { count, increment, decrement } = useCustomCounter();

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

In this example, useCustomCounter is a custom hook that encapsulates the logic for a counter.

Real-World Example

In a web application, you might create a custom hook like useFormInput to manage form input states and validations. This hook could handle the logic for updating input values, validating them, and displaying error messages. By using this custom hook, each form component can be more concise and easier to manage.

Did you find this article valuable?

Support InterviewPro: Master Tech Fundamentals by becoming a sponsor. Any amount is appreciated!