Exercises
Passing a user object
Let's update the “Prop Drilling” sandbox from a couple lessons ago so that it uses context!
Acceptance Criteria:
- A new context should be created in App.js, making the
userstate variable available to all other components - The
ModuleLessonscomponent should pluckuserfrom context, instead of receiving it through props. - No need to update
AccountDropdown, it can continue to receiveuservia props.
Code Playground
import React from 'react';
import useUser from './use-user.hook';
import AccountDropdown from './AccountDropdown';
import CourseIndexLayout from './CourseIndexLayout';
function App() {
const user = useUser();
return (
<>
<AccountDropdown user={user} />
<CourseIndexLayout />
</>
);
}
export default App;
Solution:
Video playback rate
Context is mostly used for "global" state, things that are necessary all over the application.
One example might be the “playback rate” for videos. When a user changes the playback speed for one video, it should change for all videos, no matter where they are in the app!
Let's update the sandbox below so that playbackRate is stored in context.
Acceptance Criteria:
- The
VideoPlayercomponent should receiveplaybackRatethrough context, rather than through props. - The
VideoPlayercomponent should also receive the setter function,setPlaybackRate, through context instead of props.
Code Playground
import React from 'react';
import VideoPlayer from './VideoPlayer';
function App() {
const [playbackRate, setPlaybackRate] = React.useState('1');
return (
<main>
<h1>Video Archives</h1>
{DATA.map(({ id, video, createdBy, license }) => (
<article key={id}>
<VideoPlayer
src={video.src}
caption={video.caption}
playbackRate={playbackRate}
setPlaybackRate={setPlaybackRate}
/>
<dl>
<dt>Created by</dt>
<dd>{createdBy}</dd>
<dt>Licensed under</dt>
<dd>{license}</dd>
</dl>
</article>
))}
</main>
);
}
const DATA = [
{
id: 'snowstorm',
video: {
src: 'https://sandpack-bundler.vercel.app/videos/snowstorm.mp4',
caption: 'A peaceful snowstorm in a residential area',
},
createdBy: 'Karolina Grabowska',
license: 'Creative Commons Zero (CC0)',
},
{
id: 'flowers',
video: {
src: 'https://sandpack-bundler.vercel.app/videos/flowers.mp4',
caption: 'Macro video of a flower blowing in the wind',
},
createdBy: 'Imam Hossain',
license: 'Creative Commons Zero (CC0)',
},
{
id: 'plane',
video: {
src: 'https://sandpack-bundler.vercel.app/videos/plane.mp4',
caption: 'Plane flying over the clouds',
},
createdBy: 'Ahmet Akpolat',
license: 'Creative Commons Zero (CC0)',
},
];
export default App;
Solution: