From ac86bd9ce929985e4ad3979935cda39aca8bb422 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Fri, 8 Aug 2025 13:38:38 +0530 Subject: [PATCH 1/3] [Edit] React: Context --- content/react/concepts/context/context.md | 176 +++++++++++++++++++++- 1 file changed, 169 insertions(+), 7 deletions(-) diff --git a/content/react/concepts/context/context.md b/content/react/concepts/context/context.md index 86b99e505dc..43d5d7849cd 100644 --- a/content/react/concepts/context/context.md +++ b/content/react/concepts/context/context.md @@ -1,22 +1,184 @@ --- Title: 'Context' -Description: 'In React, Context can be used to manage state globally without the need of prop drilling.' +Description: 'Enables data sharing across the component tree without passing props down manually at every level.' Subjects: + - 'Mobile Development' - 'Web Development' Tags: - - 'Components' - 'React' + - 'Components' CatalogContent: - 'react-101' - 'paths/front-end-engineer-career-path' --- -The **Context** API in [React](https://www.codecademy.com/resources/docs/react) is an easy way to manage the state of some information. It lets the parent [component](https://www.codecademy.com/resources/docs/react/components) pass the information down to any other component further down the tree hierarchy without needing to pass it as a [prop](https://www.codecademy.com/resources/docs/react/props). It can be used in combination with the [`useState()`](https://www.codecademy.com/resources/docs/react/hooks/useState) hook to change the state. Typical use cases are passing themes (e.g. color, paddings, font sizes, etc.) or the authenticated user. +**Context** in [React](https://www.codecademy.com/resources/docs/react) is a feature that allows data to be shared across the component tree without passing props manually at every level. It solves the prop drilling problem by enabling [components](https://www.codecademy.com/resources/docs/react/components) to access shared state directly, no matter their depth in the hierarchy. This is useful when multiple components at different nesting levels need access to the same data, such as authentication state, theme preferences, or application settings. + +## Implementation Methods + +Context is implemented using three core React APIs: + +- `createContext()`: Creates a new context object that can hold and share data +- `Context.Provider`: A component that supplies the context value to its descendants +- `useContext()`: A React hook that consumes context values within functional components + +The typical setup is: + +1. Create a context using `createContext()` with an optional default value. +2. Wrap components needing access in `Context.Provider` and pass the shared value via the `value` prop. +3. Use `useContext()` in child components to consume the nearest context value. + +## Example 1: Theme Management with React Context + +This example demonstrates creating a theme context for managing application-wide color themes: + +```jsx +import React, { createContext, useContext, useState } from 'react'; + +// Define context type +interface ThemeContextType { + theme: 'light' | 'dark'; + toggleTheme: () => void; +} + +// Create context with default value +const ThemeContext = + createContext < + ThemeContextType > + { + theme: 'light', + toggleTheme: () => {}, + }; + +// Provider component +const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ + children, +}) => { + const [theme, setTheme] = (useState < 'light') | ('dark' > 'light'); + + const toggleTheme = () => { + setTheme((prev) => (prev === 'light' ? 'dark' : 'light')); + }; + + return ( + + {children} + + ); +}; + +// Consumer component +const ThemedButton: React.FC = () => { + const { theme, toggleTheme } = useContext(ThemeContext); + + return ( + + ); +}; + +// Main app +const App: React.FC = () => ( + +
+

Theme Example

+ +
+
+); + +export default App; +``` + +The `ThemeContext` holds the current theme and a function to toggle it. `ThemeProvider` manages the state, while `ThemedButton` consumes it for UI changes. + +## Example 2: Sharing User Data with React Context + +This example demonstrates sharing user information across components without prop drilling: + +```jsx +import React, { createContext, useContext, useState } from 'react'; + +// Define user type +interface User { + name: string; + role: string; +} + +// Create context +const UserContext = (createContext < User) | (null > null); + +// Provider +const UserProvider: React.FC<{ children: React.ReactNode }> = ({ + children, +}) => { + const [user] = + useState < + User > + { + name: 'John Doe', + role: 'Administrator', + }; + + return {children}; +}; + +// Consumers +const Header: React.FC = () => { + const user = useContext(UserContext); + + return ( +
+

Welcome, {user?.name}!

+
+ ); +}; + +const UserProfile: React.FC = () => { + const user = useContext(UserContext); + + return ( +
+

User Profile

+

Name: {user?.name}

+

Role: {user?.role}

+
+ ); +}; + +// Main app +const App: React.FC = () => ( + +
+ + +); + +export default App; +``` + +The `UserContext` stores user information. Both `Header` and `UserProfile` read from the same source without manually passing props. + +## Frequently Asked Questions + +### 1. Why do we need to use Context? + +It avoids passing props through multiple layers when many components need the same data. This makes code easier to maintain. -## Benefit +### 2. Is React Context a hook? -Normally, information on values is passed between components as props. But sometimes it has to be passed down several levels in the tree, also called `prop drilling`. In larger applications, this can be complicated and lead to code that is hard to maintain. With `Context` this is no longer necessary. +No, React Context is not a hook. Context is a feature consisting of `createContext()` and Provider/Consumer components. However, `useContext()` is a hook that allows functional components to consume context values. -## API Implementation +### 3. When to use React Context vs Redux? -To implement the Context API, it's necessary to first create the Context using [`createContext()`](https://www.codecademy.com/resources/docs/react/context/createContext). Afterward, the [`useContext()`](https://www.codecademy.com/resources/docs/react/hooks/useContext) hook can be used to read the context from the appropriate component. +Use Context for simpler state management like themes, user data, or small-to-medium applications. Choose Redux for complex applications with frequent state updates, complex state logic, and when you need advanced debugging tools. From 3f2f71befdd1dff621275b3bfb49eaf2e8089c10 Mon Sep 17 00:00:00 2001 From: Avdhoot <50920321+avdhoottt@users.noreply.github.com> Date: Tue, 12 Aug 2025 22:08:17 +0530 Subject: [PATCH 2/3] Update content/react/concepts/context/context.md --- content/react/concepts/context/context.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/react/concepts/context/context.md b/content/react/concepts/context/context.md index 43d5d7849cd..c31d734dc65 100644 --- a/content/react/concepts/context/context.md +++ b/content/react/concepts/context/context.md @@ -18,9 +18,9 @@ CatalogContent: Context is implemented using three core React APIs: -- `createContext()`: Creates a new context object that can hold and share data +- [`createContext()`](https://www.codecademy.com/resources/docs/react/context/createContext): Creates a new context object that can hold and share data - `Context.Provider`: A component that supplies the context value to its descendants -- `useContext()`: A React hook that consumes context values within functional components +- [`useContext()`](https://www.codecademy.com/resources/docs/react/context/createContext): A React hook that consumes context values within functional components The typical setup is: From 936d46d926c21128ceb30ff7b83c1cc8d8751f06 Mon Sep 17 00:00:00 2001 From: Avdhoot Fulsundar Date: Tue, 12 Aug 2025 22:11:41 +0530 Subject: [PATCH 3/3] Changes --- content/react/concepts/context/context.md | 25 ++++++++--------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/content/react/concepts/context/context.md b/content/react/concepts/context/context.md index c31d734dc65..980a53f27bb 100644 --- a/content/react/concepts/context/context.md +++ b/content/react/concepts/context/context.md @@ -30,18 +30,16 @@ The typical setup is: ## Example 1: Theme Management with React Context -This example demonstrates creating a theme context for managing application-wide color themes: +This example shows how to create a theme context for switching between light and dark modes across the entire application: ```jsx import React, { createContext, useContext, useState } from 'react'; -// Define context type interface ThemeContextType { theme: 'light' | 'dark'; toggleTheme: () => void; } -// Create context with default value const ThemeContext = createContext < ThemeContextType > @@ -50,14 +48,13 @@ const ThemeContext = toggleTheme: () => {}, }; -// Provider component const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children, }) => { const [theme, setTheme] = (useState < 'light') | ('dark' > 'light'); const toggleTheme = () => { - setTheme((prev) => (prev === 'light' ? 'dark' : 'light')); + setTheme((previousTheme) => (previousTheme === 'light' ? 'dark' : 'light')); }; return ( @@ -67,7 +64,6 @@ const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ ); }; -// Consumer component const ThemedButton: React.FC = () => { const { theme, toggleTheme } = useContext(ThemeContext); @@ -80,6 +76,7 @@ const ThemedButton: React.FC = () => { padding: '10px 20px', border: 'none', borderRadius: '4px', + cursor: 'pointer', }} > Switch to {theme === 'light' ? 'dark' : 'light'} theme @@ -87,11 +84,10 @@ const ThemedButton: React.FC = () => { ); }; -// Main app const App: React.FC = () => (
-

Theme Example

+

Theme Context Example

@@ -104,21 +100,18 @@ The `ThemeContext` holds the current theme and a function to toggle it. `ThemePr ## Example 2: Sharing User Data with React Context -This example demonstrates sharing user information across components without prop drilling: +This example shows how to share user information across multiple components without passing props manually through each level: ```jsx import React, { createContext, useContext, useState } from 'react'; -// Define user type interface User { name: string; role: string; } -// Create context const UserContext = (createContext < User) | (null > null); -// Provider const UserProvider: React.FC<{ children: React.ReactNode }> = ({ children, }) => { @@ -133,13 +126,12 @@ const UserProvider: React.FC<{ children: React.ReactNode }> = ({ return {children}; }; -// Consumers const Header: React.FC = () => { const user = useContext(UserContext); return (
-

Welcome, {user?.name}!

+

Welcome, {user?.name || 'Guest'}!

); }; @@ -150,13 +142,12 @@ const UserProfile: React.FC = () => { return (

User Profile

-

Name: {user?.name}

-

Role: {user?.role}

+

Name: {user?.name || 'Not logged in'}

+

Role: {user?.role || 'No role assigned'}

); }; -// Main app const App: React.FC = () => (