Isolating Implementation Details

In this lesson, we'll centralize the implementation for the user state and provider in one place.

We'll cover the following

The solution highlighted in the previous lesson works but not without some caveats.

A better solution will be to centralize the logic for the user state and Provider in one place. This is a pretty common practice. Let me show you what I mean.

UserContext.js

Instead of having the Root component manage the state for loggedInUser, we will create a new file called UserContext.js.

This file will have the related logic for updating loggedInUser. It will also expose a context Provider and Consumer to make sure loggedInUser and any updater functions are accessible from anywhere in the component tree.

This sort of modularity becomes important when you have many different context objects. For example, you could have a ThemeContext and LanguageContext object in the same app.

Extracting these into separate files and components proves more manageable and effective over time.

Consider the following:

Get hands-on with 1000+ tech skills courses.