Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🪝 What are Hooks🔄 Rules of Hooks🧠 Using useState⚙️ Using useEffect🎣 Custom Hooks📦 Built-in Hooks🔗 Combining Hooks⚡ Hooks Best Practices
Reactjs/Hooks/Custom Hooks

🎣 Custom Hooks — Reusing Hook Logic

Custom Hooks let you extract component logic into reusable functions. They're JavaScript functions that use Hooks to share state logic.


🎯 Building Custom Hooks

Custom Hooks are functions that start with "use" and can call other Hooks. They let you extract component logic and reuse it across components.

import { useState, useEffect } from 'react';

// Custom Hook: useCounter
function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);

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

  return { count, increment, decrement, reset };
}

// Using the custom Hook
function Counter() {
  const { count, increment, decrement } = useCounter(0);

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

💡 Custom Hook Patterns

Custom Hooks can wrap state logic, effects, or combine other Hooks. They make components cleaner and logic reusable.

// useLocalStorage: Persist state to localStorage
function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const item = localStorage.getItem(key);
    return item ? JSON.parse(item) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

// Usage
function UserForm() {
  const [name, setName] = useLocalStorage('name', '');

  return (
    <input
      value={name}
      onChange={(e) => setName(e.target.value)}
      placeholder="Your name"
    />
  );
}

📊 Summary

ElementPurpose
Custom HookExtract and share state logic
NamingStart with "use" prefix
ReturnsState, functions, or objects

🔑 Key Takeaways

  • ✅ Custom Hooks are functions that use Hooks
  • ✅ They extract logic for reuse
  • ✅ Names must start with "use"
  • ✅ Can use multiple Hooks inside
  • ✅ Return state and functions
  • ✅ Simplify components significantly

Ready to practice? Challenges


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn