Exercise 1: Create a Context for User Information

import React, { createContext } from 'react';

const UserContext = createContext();

export default UserContext;

Exercise 2: Provide Context in the App Component


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


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