Course
useContext
React Mastery Guide
Unlock the full potential of React with our comprehensive guide. From basics to advanced techniques, this course covers everything you need to build dynamic, high-performance web applications. Perfect for developers at any level, start mastering React today!
useContext
useContext is typically used to pass data across different layers of components, providing a more straightforward way to manage global state, themes, authentication data.
Step 1: Create a Context
First, you need to create a context using
React.createContext()
. This is typically done in a new file or at the top level of your component hierarchy.import React from 'react';
const MyContext = createContext(defaultValue);
Step 2: Provide Context Value
Use a
Context.Provider
to pass the context value down the component tree. The Provider
should wrap any components that need access to this context.import React, { useState } from 'react';import MyContext from './MyContext';
function App() { const [value, setValue] = useState("Hello, Context!");
return ( <MyContext.Provider value={value}> <ChildComponent /> </MyContext.Provider> );}
Let's look at an example.
import { createContext, useContext, useState } from 'react';import './App.css';
const CountContext = createContext(-1);
const ComponentA = () => { const count = useContext(CountContext);
return ( <div style={{ marginTop: 10 }}> Count in component A: {count} <ComponentB /> </div> );};
const ComponentB = () => { const count = useContext(CountContext);
return <div style={{ marginTop: 10 }}>Count in component B: {count}</div>;};
function App() { let [count, setCount] = useState(0);
return ( <> <h1>React Hooks</h1> <div className="card"> <CountContext.Provider value={count}> <ComponentA /> </CountContext.Provider> <p>Count:{count}</p> <div className="button-container"> <button onClick={() => setCount((v) => v + 1)}>Plus one</button> </div> <p> Edit <code>src/App.tsx</code> and save to test Hooks </p> </div> <p className="read-the-docs"> Click on the Vite and React logos to learn more </p> </> );}
export default App;
Try it out!