πŸ”15. useContext() & Hook in React – Full Explanation with Real-Life Example

Payal PorwalPayal Porwal
5 min read

πŸ”Ή What is useContext() in React?

πŸ“Œ Definition:

useContext() is a React hook that allows you to access data from a Context without needing to pass props manually at every level of the component tree.

🧠 Why do we need it?

Imagine you want to share the logged-in user’s name or theme (dark/light) across multiple components β€” instead of passing it as props from parent to child again and again, you can store it in a context and access it anywhere using useContext().


πŸ› οΈ Real-life Example: Theme Toggle with useContext()

Let’s say we want to switch between light and dark mode in multiple components.

🧩 Step-by-Step Code:

1. Create a context

// ThemeContext.js
import { createContext } from 'react';

const ThemeContext = createContext();

export default ThemeContext;

2. Wrap your App with Provider

// App.js
import React, { useState } from 'react';
import ThemeContext from './ThemeContext';
import Home from './Home';

function App() {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Home />
    </ThemeContext.Provider>
  );
}

export default App;

3. Use useContext to get value

// Home.js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';

function Home() {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <div style={{ backgroundColor: theme === 'light' ? "#fff" : "#333", color: theme === 'light' ? "#000" : "#fff" }}>
      <h1>Home Page</h1>
      <button onClick={() => setTheme(theme === 'light' ? "dark" : "light")}>
        Switch Theme
      </button>
    </div>
  );
}

export default Home;

βœ… Topics covered:

  • Context API

  • useContext hook

  • Passing data globally

  • Real-life theme toggling


πŸ”Ή What is useRef() in React?

πŸ“Œ Definition:

useRef() is a React hook that gives you a way to store a mutable value that does not trigger re-render when changed. It also allows direct access to DOM elements.

🧠 Why do we need it?

  • To keep reference of a DOM element (like focusing an input box)

  • To store values across renders without causing re-render (e.g., a timer ID or previous value)


πŸ› οΈ Real-life Example: Auto focus input on load

// AutoFocusInput.js
import React, { useRef, useEffect } from 'react';

function AutoFocusInput() {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus(); // Auto-focus on load
  }, []);

  return (
    <div>
      <h3>Enter your name:</h3>
      <input ref={inputRef} type="text" placeholder="Type here..." />
    </div>
  );
}

export default AutoFocusInput;

βœ… Topics covered:

  • useRef for DOM access

  • useEffect for side-effects

  • Real-life UX use-case


πŸ“˜ Summary:

HookPurposeExample Use Case
useContextShare global data (like theme or user)Theme toggle, user login state
useRefDOM access / persist value without re-renderAuto focus input, hold timer ID

Here are 2 real-life mini projects that use the useContext and useRef hooks, each with step-by-step explanations in simple English:


βœ… Project 1: Theme Toggler App (using useContext)

πŸ’‘ Purpose:

Allow users to switch between light and dark mode using context (globally).


πŸ”§ Features:

  • Global theme management using useContext

  • Light/Dark toggle

  • Simple UI styling using CSS


🧱 Folder Structure:

src/
β”œβ”€β”€ ThemeContext.js
β”œβ”€β”€ App.js
β”œβ”€β”€ Navbar.js
β”œβ”€β”€ MainContent.js
└── index.css

🧠 Step-by-step Code:

1️⃣ Create a context: ThemeContext.js

import React, { createContext, useState } from 'react';

export const ThemeContext = createContext();

export function ThemeProvider({ children }) {
  const [isDark, setIsDark] = useState(false);

  function toggleTheme() {
    setIsDark(prev => !prev);
  }

  return (
    <ThemeContext.Provider value={{ isDark, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

2️⃣ Wrap App with Provider: App.js

import React from 'react';
import { ThemeProvider } from './ThemeContext';
import Navbar from './Navbar';
import MainContent from './MainContent';

function App() {
  return (
    <ThemeProvider>
      <Navbar />
      <MainContent />
    </ThemeProvider>
  );
}

export default App;

3️⃣ Navbar Component: Navbar.js

import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function Navbar() {
  const { isDark, toggleTheme } = useContext(ThemeContext);

  return (
    <nav className={isDark ? "dark" : "light"}>
      <h2>Theme Toggler App</h2>
      <button onClick={toggleTheme}>
        Switch to {isDark ? "Light" : "Dark"} Mode
      </button>
    </nav>
  );
}

export default Navbar;

4️⃣ MainContent Component: MainContent.js

import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function MainContent() {
  const { isDark } = useContext(ThemeContext);

  return (
    <div className={isDark ? "dark" : "light"}>
      <p>This is the main content area.</p>
    </div>
  );
}

export default MainContent;

5️⃣ Styling in index.css

.light {
  background-color: white;
  color: black;
  padding: 20px;
}

.dark {
  background-color: #222;
  color: white;
  padding: 20px;
}

button {
  padding: 10px 20px;
  margin-left: 20px;
}

πŸ“˜ React Topics Covered:

  • useContext

  • Props drilling avoidance

  • Theme management

  • Functional components


βœ… Project 2: Simple Form Focus App (using useRef)

πŸ’‘ Purpose:

Auto-focus input field on component load and reset focus on form submission.


πŸ”§ Features:

  • Auto-focus

  • useRef for DOM reference

  • Reset and refocus on submit


🧱 Folder Structure:

src/
β”œβ”€β”€ App.js
└── index.css

🧠 Step-by-step Code:

1️⃣ App Component: App.js

import React, { useRef } from 'react';
import './index.css';

function App() {
  const inputRef = useRef(null);

  function handleSubmit(e) {
    e.preventDefault();
    alert("Form Submitted");
    inputRef.current.value = "";      // clear input
    inputRef.current.focus();         // set focus again
  }

  return (
    <div className="container">
      <h2>Auto Focus Form</h2>
      <form onSubmit={handleSubmit}>
        <input type="text" ref={inputRef} placeholder="Enter something..." />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default App;

2️⃣ Styling in index.css

.container {
  width: 300px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ccc;
}

input, button {
  padding: 10px;
  width: 100%;
  margin-top: 10px;
}

πŸ“˜ React Topics Covered:

  • useRef for referencing DOM elements

  • Form submission handling

  • Reset and auto-focus


πŸ”” Stay Connected

If you found this article helpful and want to receive more such beginner-friendly and industry-relevant React notes, tutorials, and project ideas β€”
πŸ“© Subscribe to our newsletter by entering your email below.

And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment,
πŸŽ₯ Don’t forget to subscribe to my YouTube channel – Knowledge Factory 22 – for regular content on tech concepts, career tips, and coding insights!

Stay curious. Keep building. πŸš€

0
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: πŸš€ In-depth explorations of emerging technologies πŸ’‘ Practical tutorials and how-to guides πŸ”§Insights on software development best practices πŸš€Reviews of the latest tools and frameworks πŸ’‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟