Learn to create and dynamically update a Context in React. Understand how changes in the context values are reflected across components that consume the context.
-
Create an 'Exercises' Directory (If not already done):
- Create a directory on your local machine to house all your exercises, using
mkdir Exercises
.
- Create a directory on your local machine to house all your exercises, using
-
Fork the Repository:
- Navigate to the GitHub repository for this exercise at
03-26-creating-updating-context
. - Click on the 'Fork' button to create a fork of the repository.
- Navigate to the GitHub repository for this exercise at
-
Clone Your Forked Repository:
- Open the terminal.
- Navigate to your
Exercises
directory withcd path/to/Exercises
. - Run
git clone <your-forked-repo-url>
to clone the repository to your machine, creating a new directory named03-26-creating-updating-context
.
-
Initial Setup:
- Change to the exercise directory:
cd 03-26-creating-updating-context
. - Run
npm install
to install dependencies.
- Change to the exercise directory:
-
Create and Export UserContext:
- In
src
, createUserContext.js
. - Define
UserContext
usingReact.createContext()
with default user values (e.g.,{ name: 'John Doe', age: 30 }
). - Export
UserContext
.
- In
-
Create UserProfile Component:
- Create
UserProfile.js
. - Use
useContext(UserContext)
to access and display the user's name and age.
- Create
-
Implement Context Value Updates in App:
- In
App.js
, importUserContext
andUserProfile
. - Use
useState
to create a state that holds user information. - Wrap
UserProfile
withUserContext.Provider
, passing the state as the context value. - Add functionality to change the user information (e.g., a button to change the user's name).
- In
-
Observing Context Changes:
- Observe how changing the state in
App.js
updates the context values and how these changes are reflected inUserProfile
.
- Observe how changing the state in
UserProfile
displays the initial user information fromUserContext
.- Modifications to the user information in
App.js
are reflected inUserProfile
.
-
Commit Your Changes:
- Save all changes.
- Use
git add .
, thengit commit -m "Completed Creating and Updating Context exercise"
. - Push the commit to your forked repository with
git push
.
-
Create a Pull Request:
- Go to your repository on GitHub.
- Initiate a 'Pull Request' to the original repository.
- Describe your implementation in the pull request details.