Before learning about React context in depth, let's recap what we implemented in the earlier chapters, in order to get a feeling for the problem that contexts solve:
- In src/App.js, we defined the user state and the dispatch function:
const [ state, dispatch ] = useReducer(appReducer, { user: '', posts: defaultPosts })
const { user, posts } = state
- Then, we passed the user state and the dispatch function to the UserBar component (and the CreatePost component):
return (
<div style={{ padding: 8 }}>
<UserBar user={user} dispatch={dispatch} />
<br />
{user && <CreatePost user={user} posts={posts} dispatch={dispatch} />}
<br />
<hr />
<PostList posts={posts} />
</div>
)
- In the src/user/UserBar.js component, we took the user state as a prop, and then passed it down to the Logout component. We also took the dispatch function as a prop, and passed it to the Logout, Login, and Register components:
export default function UserBar ({ user, dispatch }) {
if (user) {
return <Logout user={user} dispatch={dispatch} />
} else {
return (
<React.Fragment>
<Login dispatch={dispatch} />
<Register dispatch={dispatch} />
</React.Fragment>
)
}
}
- Finally, we used the dispatch and user props in the Logout, Login, and Register components.
React context allows us to skip steps 2 and 3, and jump straight from step 1 to step 4. As you can imagine, with larger apps, context becomes even more useful, because we might have to pass down props over many levels.