React Context API
ใช้ React Context API เพื่อจัดการสถานะส่วนกลางและแบ่งปันข้อมูลระหว่างคอมโพเนนต์อย่างมีประสิทธิภาพ
React Context API เป็นบทเรียน Next.js 15 Fullstack (App Router + Server Actions) ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack (App Router + Server Actions) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack (App Router + Server Actions) มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Global State?
In larger applications, components often need to share data. Passing data down through many layers of components is called prop drilling. It can make your code hard to read and maintain.
React Context API helps solve this by providing a way to share state across the component tree without manually passing props at each level.
Meet React Context
React Context provides a way to pass data through the component tree without having to pass props down manually at every level.
It's designed to share "global" data for a tree of React components, like the current authenticated user, theme, or preferred language.
Define Your Context
The first step is to create a Context object using React.createContext(). You can give it a default value, which is used when a component tries to consume the context without a matching Provider above it in the tree.
// Simulate React environment
const createContext = (defaultValue) => ({
_value: defaultValue, // Internal storage for the context value
Provider: function({ value, children }) {
this._value = value; // Update internal value when Provider is used
return children; // Simulate rendering children
},
get value() { return this._value; } // Getter for useContext
});
// --- Your Context ---
const ThemeContext = createContext('light');
// --- Entry point (simulated) ---
function main() {
console.log("ThemeContext default value:", ThemeContext.value);
}
main();Making Data Available
To make the context value available to components, you wrap them with a Context Provider. The provider takes a value prop, which will be the data accessible to all components nested inside it.
You can have multiple Providers for different contexts, or even nested Providers for the same context to override values.
// Simulate React environment
const createContext = (defaultValue) => ({
_value: defaultValue,
Provider: function({ value, children }) {
this._value = value;
return children;
},
get value() { return this._value; }
});
// --- Your Context ---
const UserContext = createContext(null); // Default to no user
// --- Simulated Component Tree ---
const App = () => {
const currentUser = { name: "Coddy", id: 123 };
return UserContext.Provider({
value: currentUser,
children: "User data is now provided."
});
};
// --- Entry point ---
function main() {
App(); // Call App to set the context value
console.log("Context value after App render:", UserContext.value.name);
}
main();Accessing Context with Hook
The easiest way to read context in a functional component is using the useContext hook. It takes the Context object itself (e.g., UserContext) as an argument and returns the current context value.
When the context value changes, the component using useContext will automatically re-render.
// Simulate React environment
const createContext = (defaultValue) => ({
_value: defaultValue,
Provider: function({ value, children }) {
this._value = value;
return children;
},
get value() { return this._value; }
});
const useContext = (Context) => {
return Context.value;
};
// --- Your Context & Components ---
const LanguageContext = createContext('en');
const GreetUser = () => {
const language = useContext(LanguageContext);
return `Greeting in ${language}: Hello!`;
};
const App = () => {
return LanguageContext.Provider({
value: "es", // Provide Spanish language
children: GreetUser() // Render GreetUser inside
});
};
// --- Entry point ---
function main() {
console.log(App()); // Simulate rendering App and logging GreetUser's output
}
main();Practical Example: Theme
Let's build a simple theme switcher using Context. We'll store the current theme (e.g., 'light' or 'dark') and a function to toggle it within our context.
First, we create the context and a wrapper component, ThemeProvider, which will manage the theme state.
// Simulate React environment
let _themeState = 'light'; // Simulate useState for theme
let _setThemeState = (newTheme) => { _themeState = newTheme; };
const createContext = (defaultValue) => ({
_value: defaultValue,
Provider: function({ value, children }) {
this._value = value;
return children;
},
get value() { return this._value; }
});
// --- Theme Context ---
const ThemeContext = createContext({
theme: 'light',
toggleTheme: () => {}
});
// --- Theme Provider Component ---
const ThemeProvider = ({ children }) => {
const theme = _themeState; // Get current theme
const toggleTheme = () => {
_setThemeState(theme === 'light' ? 'dark' : 'light');
console.log("Theme toggled to:", _themeState); // Log for simulation
};
return ThemeContext.Provider({
value: { theme, toggleTheme },
children: children
});
};
// --- Entry point ---
function main() {
// Simulate initial render of ThemeProvider
ThemeProvider({ children: "Theme setup complete." });
console.log("Initial theme:", ThemeContext.value.theme);
}
main();Displaying Current Theme
Now that we have our ThemeProvider, any component nested inside it can access the theme and toggleTheme function using useContext(ThemeContext). Let's create a component to display the current theme.
// Simulate React environment (from previous scenes)
let _themeState = 'light';
let _setThemeState = (newTheme) => { _themeState = newTheme; };
const createContext = (defaultValue) => ({
_value: defaultValue,
Provider: function({ value, children }) {
this._value = value;
return children;
},
get value() { return this._value; }
});
const useContext = (Context) => {
return Context.value;
};
// --- Theme Context ---
const ThemeContext = createContext({
theme: 'light',
toggleTheme: () => {}
});
// --- Theme Provider Component ---
const ThemeProvider = ({ children }) => {
const theme = _themeState;
const toggleTheme = () => {
_setThemeState(theme === 'light' ? 'dark' : 'light');
};
return ThemeContext.Provider({
value: { theme, toggleTheme },
children: children
});
};
// --- Component to display theme ---
const ThemeDisplay = () => {
const { theme } = useContext(ThemeContext);
return `Current theme is: ${theme}`;
};
// --- App structure ---
const App = () => {
return ThemeProvider({
children: ThemeDisplay() // ThemeDisplay is nested inside Provider
});
};
// --- Entry point ---
function main() {
console.log(App()); // Simulate rendering
}
main();Adding Interactivity
To allow users to change the theme, we need a way to call the toggleTheme function provided by our ThemeProvider. We'll create a button component that uses useContext to get this function and trigger it on click.
// Simulate React environment (from previous scenes)
let _themeState = 'light';
let _setThemeState = (newTheme) => { _themeState = newTheme; };
const createContext = (defaultValue) => ({
_value: defaultValue,
Provider: function({ value, children }) {
this._value = value;
return children;
},
get value() { return this._value; }
});
const useContext = (Context) => {
return Context.value;
};
// --- Theme Context ---
const ThemeContext = createContext({
theme: 'light',
toggleTheme: () => {}
});
// --- Theme Provider Component ---
const ThemeProvider = ({ children }) => {
const theme = _themeState;
const toggleTheme = () => {
_setThemeState(theme === 'light' ? 'dark' : 'light');
console.log("Theme toggled to:", _themeState); // Log for simulation
};
return ThemeContext.Provider({
value: { theme, toggleTheme },
children: children
});
};
// --- Component to toggle theme ---
const ThemeTogglerButton = () => {
const { toggleTheme } = useContext(ThemeContext);
// Simulate button click
return `Click to toggle theme. (Calling toggleTheme function)`;
};
// --- App structure ---
const App = () => {
return ThemeProvider({
children: ThemeTogglerButton()
});
};
// --- Entry point ---
function main() {
console.log(App()); // Simulate rendering
// In a real app, a button click would call toggleTheme
ThemeContext.value.toggleTheme(); // Simulate a click
console.log("After simulated click, new theme:", _themeState);
}
main();When to Use Context
Context is great for global state, but it's not a replacement for local component state or prop drilling for simple cases.
- Global Data: Use for themes, user auth, language settings.
- Avoid for: Frequent updates (can cause many re-renders), or state only needed by a few direct children.
- Separate Contexts: Create different contexts for unrelated pieces of global state to prevent unnecessary re-renders.
Context & Performance
When a Context's value changes, all components consuming that context (via useContext) will re-render, even if they only use part of the value.
To optimize, you can:
- Split large contexts into smaller, more focused ones.
- Memoize complex objects passed as
valueto prevent unnecessary re-renders of consumers.
Quick Context Check
Which of the following statements about React Context API are TRUE?
Recap: React Context
You've learned how to use the React Context API to manage global state!
createContext: Creates a Context object.Context.Provider: Makes data available to children via itsvalueprop.useContext: Hook to consume Context data in functional components.
Context is powerful for sharing data like themes or user info across your app, reducing prop drilling.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 22
- บทเรียน
- 88
คำถามที่พบบ่อย
บทเรียน “React Context API” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “React Context API” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack (App Router + Server Actions) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack (App Router + Server Actions) มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “React Context API”
ใช้ React Context API เพื่อจัดการสถานะส่วนกลางและแบ่งปันข้อมูลระหว่างคอมโพเนนต์อย่างมีประสิทธิภาพ คุณปฏิบัติ Next.js 15 Fullstack (App Router + Server Actions) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack (App Router + Server Actions) หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack (App Router + Server Actions) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “React Context API” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack (App Router + Server Actions) นี้ได้ไหม
ได้ บทเรียน Next.js 15 Fullstack (App Router + Server Actions) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ