Introducing React Context
In the previous chapters, we passed down the username
state and setUsername
function from the App
component to the UserBar
component; and then from the UserBar
component to the Logout
, Login
, and Register
components. React Context provides a solution to this cumbersome way of passing down props over multiple levels of components, by allowing us to share values between components without having to explicitly pass them down via props. As we are going to see, contexts are perfect for sharing global state across the whole application.
Passing down props
Before learning about React Context in depth, let’s recap what we implemented in the earlier chapters to get a feeling for the problem that contexts solve. You do not need to edit any code at this point; these steps are just a recap of what we have already done. Just read along for the following steps:
- In
src/App.jsx
, we defined theusername
state andsetUsername
function using a State...