SmartCodingTips

🔁 React Hook Examples

Here's a quick reference of real-world React Hook examples including useState, useEffect, useRef, useContext, and useReducer.


🧠 useState

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click Me</button>
    </div>
  );
}

🕒 useEffect

import { useEffect } from "react";

function Timer() {
  useEffect(() => {
    const id = setInterval(() => {
      console.log("Tick");
    }, 1000);
    return () => clearInterval(id);
  }, []);
}

📦 useRef

import { useRef } from "react";

function InputFocus() {
  const inputRef = useRef(null);
  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={() => inputRef.current.focus()}>Focus Input</button>
    </div>
  );
}

🌐 useContext

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function ThemedComponent() {
  const theme = useContext(ThemeContext);
  return <p>Theme is: {theme}</p>;
}

🔄 useReducer

import { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "increment": return { count: state.count + 1 };
    case "decrement": return { count: state.count - 1 };
    default: return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </div>
  );
}

📘 Summary

  • useState handles local state
  • useEffect manages side effects
  • useRef gives direct access to DOM or persistent variables
  • useContext shares data across components
  • useReducer is great for complex state logic