π15. useContext() & Hook in React β Full Explanation with Real-Life Example

πΉ 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
hookPassing 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 accessuseEffect
for side-effectsReal-life UX use-case
π Summary:
Hook | Purpose | Example Use Case |
useContext | Share global data (like theme or user) | Theme toggle, user login state |
useRef | DOM access / persist value without re-render | Auto 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 elementsForm 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. π
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! π