Skip to content

menkar/reactjs-hooks

Repository files navigation

React Hooks — Interactive Reference Workspace

A professional, runnable catalog of React 19 hooks with live examples, nested routing, and business-oriented explanations. Built for teams who want a single place to learn, demo, and compare hook patterns used in production applications.

Author: Swapnil Menkar · Fullstack Expert · 8149005578


Overview

This project is a reference workspace, not a starter template. Each hook category maps to a folder under hooks/, with one or more components you can open in the browser. The shell application (src/App.jsx) provides:

  • Category navigation — full-width responsive grid (no horizontal scroll); each row has a hook tab plus an info (ⓘ) icon
  • Hook reference modal — click the ⓘ icon to open a centered dialog with definition, project examples, and business scenarios (does not change the route)
  • Example sub-navigation — per-hook child routes
  • Dynamic headings — title and description update per route
  • Light / dark themeuseContext + Tailwind dark variant
  • Lazy loading — examples load on demand via React.lazy and Suspense

Tech stack

Layer Technology
UI React 19, React DOM
Routing React Router DOM 7
Styling Tailwind CSS 4, PostCSS
Build Vite 6
Tooling ESLint, React Compiler (Babel)

Getting started

Prerequisites

  • Node.js >=20.19.0 (see package.json engines; your current 22.9.0 is supported)

Install and run

npm install
npm run dev

Open the URL shown in the terminal (typically http://localhost:5173).

Using the workspace

Action What happens
Click a hook tab (e.g. useReducer) Navigates to that category and loads the default or last example route
Click the ⓘ icon next to a hook Opens the hook reference modal with definition, examples in this repo, and business scenarios
Click OK, Cancel, X, backdrop, or press Escape Closes the modal; your current route is unchanged
Use example pills below the hook bar Switch between child examples for the active category
Switch to dark mode (header) Toggles theme via ThemeContext

Other scripts

npm run build    # production build
npm run preview  # preview production build
npm run lint     # ESLint

Project structure

reactjs-hooks/
├── hooks/                    # Hook examples by category
│   ├── useState/
│   ├── useEffect/
│   ├── useLayoutEffect/
│   ├── useRef/
│   ├── useContext/
│   ├── useReducer/
│   ├── useImperativeHandle/
│   ├── useId/
│   ├── useTransition/
│   ├── useDeferredValue/
│   ├── useActionState/
│   ├── useFormStatus/
│   ├── useOptimistic/
│   └── customHook/useFetch/
├── src/
│   ├── App.jsx               # Routes, layout, example sub-nav, footer
│   ├── components/
│   │   └── HookCategoryNav.jsx   # Hook tabs, ⓘ icons, reference modal
│   ├── data/
│   │   └── hookInfoCatalog.js    # Modal copy (definitions, examples, scenarios)
│   ├── main.jsx
│   └── index.css             # Tailwind + dark mode
└── README.md

Routing map

Category route Default example Child route(s)
/useState Counter /counter, /controlled-input
/useEffect Data fetcher /data-fetcher
/useLayoutEffect Chat message scroller /chat-message-scroller
/useRef Input focus /input-focus
/useContext Theme switcher /theme-switcher
/useReducer Reducer counter /reducer-counter
/useImperativeHandle Fancy input parent /fancy-input-parent, /fancy-input-child
/useId Checkbox /checkbox
/useTransition Expensive calculation /expensive-calculation
/useDeferredValue Deferred calculation /deferred-expensive-calculation
/useActionState Login form /login
/useFormStatus Form status login /form-status-login
/useOptimistic Todo list /todo
/customHook Posts (useFetch) /posts

Hooks reference

Each section below includes a definition, the example in this repo, and real-world business scenarios.

The same content is available in the app: click the icon beside any hook in the top navigation to open the hook reference modal (centered, scrollable, viewport-safe). The modal also shows each hook’s package (react or react-dom), import line, and syntax example (e.g. const [data, setData] = useState([])). Tab navigation and live examples are unchanged—only the icon opens the modal.

Modal content is maintained in src/data/hookInfoCatalog.js and rendered by src/components/HookCategoryNav.jsx.


useState

Definition
Adds local state to a function component. Updates trigger a re-render with the new value.

Examples in this project

  • hooks/useState/Counter.jsx — numeric counter
  • hooks/useState/ControlledInput.jsx — controlled text field

Business use cases

Scenario How useState helps
Form fields Hold input values, validation messages, and touched/dirty flags
UI toggles Modals, accordions, filters, and “show more” without a global store
Shopping cart (client) Line quantities and selected options before checkout API call
Dashboard widgets Independent widget settings (date range, metric) per card

useEffect

Definition
Runs side effects after render: data fetching, subscriptions, or syncing with external systems. Cleanup runs on unmount or before the next effect.

Example in this project

  • hooks/useEffect/DataFetcher.jsx — fetch posts on mount with loading and error UI

Business use cases

Scenario How useEffect helps
API data on page load Load orders, users, or KPIs when a route mounts
Analytics Fire page-view or funnel events when dependencies change
WebSocket / polling Subscribe on mount, unsubscribe on leave
Document title & SEO helpers Update document.title or meta when route params change

useLayoutEffect

Definition
Like useEffect, but runs synchronously after DOM updates and before the browser paints. Use when you must measure or mutate layout to avoid visible flicker.

Example in this project

  • hooks/useLayoutEffect/ChatMessageScroller.jsx — scroll to latest message after new items

Business use cases

Scenario How useLayoutEffect helps
Chat & comment threads Keep scroll pinned to the bottom without a flash of old position
Tooltips / popovers Measure anchor position before paint
Data grids Sync scroll headers or column widths after data changes
Print / PDF previews Adjust layout once DOM is ready, before user sees wrong alignment

useRef

Definition
Holds a mutable value that persists across renders without causing re-renders when it changes. Often used for DOM nodes or instance variables.

Example in this project

  • hooks/useRef/InputBoxFocus.jsxfocus() on input from a button click

Business use cases

Scenario How useRef helps
Focus management Move focus to search, OTP field, or error summary after submit
Media players Hold video element reference for play/pause
Interval / timer IDs Store timer handle for cleanup without extra state
Previous value tracking Compare last prop/value in effects without stale closures

useContext

Definition
Lets components read shared values from a Provider without passing props through every level.

Examples in this project

  • hooks/useContext/ThemeContext.jsx — theme state and toggle
  • hooks/useContext/ThemeSwitcher.jsx — consumer component
  • hooks/useContext/ThemeExample.jsx — demo copy on route

Business use cases

Scenario How useContext helps
Theme & branding Light/dark mode, density, or white-label settings
Auth session Current user, roles, and permissions for the subtree
Locale / i18n Language and formatting without prop drilling
Feature flags Enable modules per tenant from a single provider

useReducer

Definition
Manages complex state with a reducer (state, action) => newState and dispatch. Similar to Redux patterns inside one component or small tree.

Example in this project

  • hooks/useReducer/ReducerCounter.jsx — increment, decrement, reset, and step actions via action.amount

Business use cases

Scenario How useReducer helps
Multi-step wizards Centralize step index, validation, and draft data
Filters & faceted search One action updates several related filter fields predictably
Order builder Add/remove lines, discounts, and shipping in one state machine
Undo-friendly editors Actions describe user intent; easier to log or replay than many useState calls

useImperativeHandle

Definition
Customizes the instance value exposed to parent components when they use ref, usually with forwardRef. Hides internal DOM details behind a small API.

Examples in this project

  • hooks/useImperativeHandle/FancyInputParent.jsx — parent calls focus / clear
  • hooks/useImperativeHandle/FancyInputChild.jsx — child exposes methods via useImperativeHandle

Business use cases

Scenario How useImperativeHandle helps
Design system inputs Expose focus(), select(), clear() on wrapped fields
Maps & charts Parent triggers fitBounds() or exportImage() on encapsulated widget
Rich text / code editors Imperative API for insert, format, or scroll without leaking editor internals
Modal focus traps Child dialog exposes open() / close() with correct focus restore

useId

Definition
Generates stable unique IDs per component instance, safe for SSR and multiple instances on one page.

Example in this project

  • hooks/useId/Checkbox.jsx — links <label htmlFor> and <input id>

Business use cases

Scenario How useId helps
Accessible forms Unique ids for labels, hints, and aria-describedby
Repeated list items Each row’s controls stay correctly associated
SSR / hydration Avoid id collisions between server and client markup
Component libraries Generate ids inside primitives without central counters

useTransition

Definition
Marks state updates as non-urgent transitions. React can keep the UI responsive and show pending state while heavier updates finish.

Example in this project

  • hooks/useTransition/ExpensiveCalculation.jsx — deferred result list while typing

Business use cases

Scenario How useTransition helps
Search with heavy results Keep input snappy while result list re-renders
Tab switching Avoid blocking clicks when new tab content is expensive
Large table refresh Show tab indicator or skeleton during transition
Config panels Apply heavy preview updates without freezing sliders

useDeferredValue

Definition
Returns a lagged version of a value. Urgent updates (e.g. typing) use the latest value; expensive UI can read the deferred value.

Example in this project

  • hooks/useDeferredValue/DeferredExpensiveCalculation.jsx — previous results stay visible (stale UI) while recalculating

Business use cases

Scenario How useDeferredValue helps
Live search dashboards Show last good chart while new query computes
Product catalogs Filter text updates instantly; grid uses deferred filter
Log viewers Type fast; deferred query reduces jank on huge lists
Design tools Canvas stays interactive while preview catches up

useActionState

Definition
Manages state produced by an async form action: pending flag, returned data, and errors—aligned with React’s form actions model.

Example in this project

  • hooks/useActionState/Login.jsx — mock login with isPending and error/success messages
    Demo credentials: admin / password

Business use cases

Scenario How useActionState helps
Login & registration Single hook for submitting credentials and showing errors
Checkout submit Order placement with server validation messages
CRUD forms Create/update records with inline success and field errors
Approvals workflow Submit decision and refresh status from action result

useFormStatus

Definition
Reads the pending state of the parent <form> from a child—typically a submit button in a separate component. Requires React DOM.

Examples in this project

  • hooks/useFormStatus/FormStatusLogin.jsx — login form with useActionState
  • hooks/useFormStatus/SubmitButton.jsxisPending from useFormStatus()
    Demo credentials: admin@example.com / admin123

Business use cases

Scenario How useFormStatus helps
Shared submit bar Footer button shows “Saving…” without lifting all form state
Design system forms <SubmitButton /> works inside any parent form
Multi-section applications Disable duplicate submits while long POST runs
Accessibility Announce loading on submit control tied to form lifecycle

useOptimistic

Definition
Shows optimistic UI immediately while an async action runs; reconciles to real state when the action completes.

Example in this project

  • hooks/useOptimistic/ToDo.jsx — add todo with “(Adding…)” until confirmed

Business use cases

Scenario How useOptimistic helps
Task & ticket lists New item appears instantly; revert or confirm on API response
Reactions & likes Increment count before server ack; rollback on failure
Messaging Outgoing message in thread while send is in flight
Inventory adjustments Temporary stock display during write, then sync

Custom hook: useFetch

Definition (pattern)
Encapsulates data fetching logic (loading, error, data) in a reusable function—not a built-in React hook, but a standard enterprise pattern.

Examples in this project

  • hooks/customHook/useFetch/useFetch.jsx — fetch + cleanup on unmount
  • hooks/customHook/useFetch/Posts.jsx — consumes hook against DummyJSON posts API

Business use cases

Scenario How useFetch helps
List pages One hook per resource (useOrders, useCustomers) with consistent UX
Admin consoles Reuse loading/error handling across dozens of screens
Micro-frontends Shared data layer contract for teams
Testing Mock the hook instead of every fetch call in components

Quick comparison: when to use which

Need Prefer
Simple local UI state useState
Fetch / subscribe on mount or deps useEffect
Measure DOM before paint useLayoutEffect
DOM API without re-render useRef
Shared tree-wide settings useContext
Many related state transitions useReducer
Parent controls child via ref useImperativeHandle
Stable ids for a11y useId
Heavy update, keep UI responsive useTransition
Defer derived value for expensive UI useDeferredValue
Async form submit + result state useActionState
Submit button outside form body useFormStatus
Instant UI before server confirms useOptimistic
Reusable fetch logic Custom useFetch

Design notes

  • Palette: Slate neutrals with blue accents (blue-800 / blue-900) for a business-friendly look in the shell and modal header.
  • Responsive layout: Full-width shell; hook tabs use a responsive grid (2–8 columns by breakpoint); example pills wrap on small screens.
  • Hook reference modal: Centered dialog with gradient header, scrollable body (max-h ~85% viewport), X / Cancel / OK close actions, backdrop click and Escape support; body scroll locked while open.
  • Navigation separation: Hook tabs use NavLink for routing; buttons are separate controls so users can read reference material without leaving the current example.
  • Accessibility: Skip link, form labels, role="dialog" / aria-modal on the reference modal, aria-label on info buttons, role="status" / role="alert" in examples where appropriate.

License & usage

Private learning and demonstration project. Examples use public mock APIs (e.g. JSONPlaceholder, DummyJSON) for education only.


Contact

Swapnil Menkar — Fullstack Expert

About

React JS all types of hooks demo

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors