Building a Theme Toggler with useContext

๐ŸŒ— Building a Theme Toggler with useContext in React

React's useContext hook is perfect for managing global state like a dark/light theme toggle.


๐Ÿง  What is useContext?

useContext allows you to share values (like a theme) between components without passing props manually at every level.


๐Ÿ› ️ Step-by-Step: Build the Theme Toggler

1. Create the Theme Context

jsx

Copy

Edit

// ThemeContext.js

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


export const ThemeContext = createContext();


export const ThemeProvider = ({ children }) => {

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


  const toggleTheme = () => {

    setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));

  };


  return (

    <ThemeContext.Provider value={{ theme, toggleTheme }}>

      {children}

    </ThemeContext.Provider>

  );

};

2. Wrap Your App with the Theme Provider

jsx

Copy

Edit

// App.js

import React from 'react';

import { ThemeProvider } from './ThemeContext';

import Home from './Home';


function App() {

  return (

    <ThemeProvider>

      <Home />

    </ThemeProvider>

  );

}


export default App;

3. Consume Context in a Component

jsx

Copy

Edit

// Home.js

import React, { useContext } from 'react';

import { ThemeContext } from './ThemeContext';


function Home() {

  const { theme, toggleTheme } = useContext(ThemeContext);


  const style = {

    backgroundColor: theme === 'light' ? '#ffffff' : '#333333',

    color: theme === 'light' ? '#000000' : '#ffffff',

    height: '100vh',

    display: 'flex',

    flexDirection: 'column',

    alignItems: 'center',

    justifyContent: 'center'

  };


  return (

    <div style={style}>

      <h1>{theme.toUpperCase()} MODE</h1>

      <button onClick={toggleTheme}>Toggle Theme</button>

    </div>

  );

}


export default Home;

๐Ÿงช Try It Out

When you click the Toggle Theme button, the theme switches between light and dark using useContext.


✅ Key Points

useContext simplifies global state sharing.


Contexts are great for theme, language, user auth, etc.


Keep context providers near the top of your app for full access.


Would you like to add theme persistence with localStorage, or style it with Tailwind or CSS modules next?

Learn React JS Course in Hyderabad

Read More

How to Use useLayoutEffect Effectively

React Hook Rules You Should Never Break

Visit Our Quality Thought Training in Hyderabad

Get Directions 



Comments

Popular posts from this blog

Entry-Level Cybersecurity Jobs You Can Apply For Today

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Installing Tosca: Step-by-Step Guide for Beginners