Updating Context Values
Learn how to update shared Context values using React state and make the latest values available to consuming components.
1. What Does Updating Context Mean?
Context allows components to access shared information. When that information needs to change, React state can hold the current value and pass it to a Context Provider.
For example, a student portal may display a student's name and course in several components. When the student details change, the application can update its state and provide the new information through Context.
2. Understanding the Update Flow
A component calls a state setter, React renders the component with the updated state, and the Provider supplies the new value to its consumers.
3. Updating a Simple Theme Value
First, create a Context that stores the theme. The default value will be used only when no matching Provider exists.
import { createContext } from 'react';
const ThemeContext = createContext('light');
export default ThemeContext;
Now manage the theme using useState and provide it to a component.
import { useState } from 'react';
import ThemeContext from './ThemeContext';
import ThemeDisplay from './ThemeDisplay';
function App() {
const [theme, setTheme] = useState('light');
function changeTheme() {
setTheme('dark');
}
return (
<ThemeContext.Provider value={theme}>
<ThemeDisplay />
<button onClick={changeTheme}>
Change Theme
</button>
</ThemeContext.Provider>
);
}
export default App;
import { useContext } from 'react';
import ThemeContext from './ThemeContext';
function ThemeDisplay() {
const theme = useContext(ThemeContext);
return (
<h2>Current Theme: {theme}</h2>
);
}
export default ThemeDisplay;
Expected Output
Initially: Current Theme: light
After clicking Change Theme: Current Theme: dark
The state setter changes the theme. The Provider receives the new theme value, and ThemeDisplay reads the updated value through useContext.
4. Updating an Object Stored in Context
Context can also distribute objects containing multiple related values. When updating an object in React state, create a new object instead of modifying the existing one.
import { createContext } from 'react';
const StudentContext = createContext(null);
export default StudentContext;
import { useState } from 'react';
import StudentContext from './StudentContext';
import StudentDetails from './StudentDetails';
function App() {
const [student, setStudent] = useState({
name: 'Samadhan',
course: 'React Development'
});
function updateStudent() {
setStudent({
name: 'Samiksha',
course: 'Data Analytics'
});
}
return (
<StudentContext.Provider value={student}>
<StudentDetails />
<button onClick={updateStudent}>
Update Student
</button>
</StudentContext.Provider>
);
}
export default App;
import { useContext } from 'react';
import StudentContext from './StudentContext';
function StudentDetails() {
const student = useContext(StudentContext);
return (
<div>
<h2>Student Details</h2>
<p>Name: {student.name}</p>
<p>Course: {student.course}</p>
</div>
);
}
export default StudentDetails;
Expected Output
Before clicking:
Name: Samadhan
Course: React Development
After clicking Update Student:
Name: Samiksha
Course: Data Analytics
5. Updating One Property While Preserving Others
Sometimes only one property needs to change. Use the spread operator to preserve the other properties in the state object.
const [student, setStudent] = useState({
name: 'Samadhan',
course: 'React Development',
city: 'Pune'
});
function updateCourse() {
setStudent(previousStudent => ({
...previousStudent,
course: 'Data Analytics'
}));
}
Explanation
previousStudentrepresents the previous state value....copies the existing properties into a new object.courseis overwritten with the new course name.- The name and city remain unchanged.
Expected Updated Data
Name: Samadhan
Course: Data Analytics
City: Pune
6. Updating Context for Multiple Components
Several components can consume the same Context. When the Provider value changes, all components reading that Context receive the latest value.
import { useContext } from 'react';
import StudentContext from './StudentContext';
function StudentName() {
const student = useContext(StudentContext);
return <h2>Student: {student.name}</h2>;
}
export default StudentName;
import { useContext } from 'react';
import StudentContext from './StudentContext';
function StudentCourse() {
const student = useContext(StudentContext);
return <p>Course: {student.course}</p>;
}
export default StudentCourse;
Place both components inside the same Provider and use the state-update example from Section 4.
Expected Behavior
Before update: Student: Samadhan
Before update: Course: React Development
After update: Student: Samiksha
After update: Course: Data Analytics
7. Common Mistakes
Mistake 1: Mutating State Directly
student.name = 'Samiksha';
Do not directly modify an object held in React state. Instead, create a new object and pass it to the state setter.
Mistake 2: Forgetting to Pass State to the Provider
If the Provider continues receiving a fixed value, changing a separate state variable will not change the value supplied by that Provider. Pass the current state value to its value prop.
Mistake 3: Forgetting to Call the State Setter
Updating a normal variable does not trigger the same React state update behavior. Use the setter returned by useState.
Mistake 4: Expecting Context to Update Itself
Context does not automatically manage changing data. Use React state or another state-management mechanism to produce and update the value.
8. Best Practices
- Keep changing values in React state.
- Pass the current state value to the Provider.
- Use state setters to update values.
- Create new objects when updating object state.
- Use the spread operator when preserving existing properties.
- Keep Context values organized and easy to understand.
- Use Context only when the value needs to be shared with descendant components.
9. Practice Tasks
Complete the following tasks.
- Create a ThemeContext and switch between light and dark themes using a button.
- Create a StudentContext with name and course properties.
- Update the student name when a button is clicked.
- Change only the course property while preserving the other object properties.
- Display the updated Context value in two different components.
- Explain why React state should not be mutated directly.
- Explain how a state update changes the value supplied by a Provider.
Summary
Updating Context values usually involves managing data with React state and passing the current state value to a Context Provider. When a state setter provides a new value, React renders the relevant component and updates consumers that read the changed Context. Use new objects for object-state updates and the spread operator to preserve properties that should not change. Context shares the value, while state manages its updates.