Exercise 1: Create a Context for User Information
App
application, create a new context called UserContext
that will hold the user’s information (name
, age
, and incrementAge
function).UserContext.jsx
and set up the context.import React, { createContext } from 'react';
const UserContext = createContext();
export default UserContext;
Exercise 2: Provide Context in the App
Component
UserInfo
and Counter
components within a UserContext.Provider
in the App.jsx
component.incrementAge
function as the context value.
import React, { useState } from 'react';
import Counter from './Counter';
import UserInfo from './UserInfo';
import UserContext from './UserContext';
const App = () => {
const [count, setCount] = useState(0);
const [user, setUser] = useState({ name: 'John Doe', age: 25 });
const incrementCount = () => {
setCount(count + 1);
};
const incrementAge = () => {
setUser({ ...user, age: user.age + 1 });
};
const contextValue = {
name: user.name,
age: user.age,
incrementAge,
};
return (
<UserContext.Provider value={contextValue}>
<h1>Dashboard</h1>
<Counter count={count} incrementCount={incrementCount} />
<UserInfo />
</UserContext.Provider>
);
};
export default App;
Exercise 3: Consume the Context in UserInfo
UserInfo.jsx
to consume the context instead of receiving props directly.useContext
hook to access the user’s name, age, and incrementAge
function from UserContext
.
import React, { useContext } from 'react';
import UserContext from './UserContext';
const UserInfo = () => {
const { name, age, incrementAge } = useContext(UserContext);
return (
<div>
<h2>User Info</h2>
<p>Name: {name}</p>
<p>Age: {age}</p>
<button onClick={incrementAge}>Increase Age</button>
</div>
);
};
export default UserInfo;
Exercise 4: Test the Application
UserInfo
component correctly displays the user’s name and age, and that clicking the "Increase Age" button updates the age.UserInfo
in App.jsx
.