0
0
Reactframework~30 mins

Creating context in React - Try It Yourself

Choose your learning style9 modes available
Creating context
📖 Scenario: You are building a simple React app that shares a theme color across multiple components without passing props manually.
🎯 Goal: Create a React context to hold a theme color and use it in a child component to display the current theme.
📋 What You'll Learn
Create a React context with a default value
Create a provider component that uses the context
Consume the context value in a child component using useContext hook
Render the child component inside the provider to show the theme color
💡 Why This Matters
🌍 Real World
React context is used to share data like themes, user info, or settings across many components without passing props manually.
💼 Career
Understanding React context is essential for building scalable React apps and working on modern frontend projects.
Progress0 / 4 steps
1
Create the ThemeContext
Create a React context called ThemeContext with the default value 'light' using createContext.
React
Need a hint?

Use createContext('light') to create the context with default value 'light'.

2
Create ThemeProvider component
Create a functional component called ThemeProvider that returns ThemeContext.Provider with the value 'dark' and renders its children inside.
React
Need a hint?

Wrap {children} inside ThemeContext.Provider with value 'dark'.

3
Create ThemedText component consuming context
Create a functional component called ThemedText that uses useContext(ThemeContext) to get the theme and returns a <p> element displaying Current theme: followed by the theme value.
React
Need a hint?

Use const theme = useContext(ThemeContext) inside the component and display it in a paragraph.

4
Render ThemedText inside ThemeProvider
Create a functional component called App that returns ThemeProvider wrapping the ThemedText component.
React
Need a hint?

Return <ThemeProvider><ThemedText /></ThemeProvider> inside App.