Context in PracticeContext in Practice

Let's create a blog source about the planets. We will use Context to avoid prop drilling. The app will consist of the following components: App, Filter, PlanetList, and PlanetItem. To visualize their hierarchy, please refer to the image below.


Step 1

Create the Context in the context.js file at the top level.

Step 2

Let the entire app know that we are using context. So, we need to wrap the whole app with the Context.Provider in the App.jsx file.

Step 3

At this step, we must set the context's data (value prop for the Context.Provider component). Let's begin by rendering some data. Data is presented in the form of the array of objects:

Here's what we'll do:

Import data from the data.js file

Initialize the state for the planets as an empty array using the useState hook.

Use the useEffect hook to assign the imported data to the planets variable. This ensures that we have data to render.

Create the variable appData, representing the entire app data, which will be an object with the planets state.

Assign the appData variable to the value prop of the context provider.

Full code of the App.jsx file after the step three.

Step 4

Let's take a look at the PlanetList component. Its purpose is to render a specific markup. Inside this markup, we utilize the PlanetItem component. It's worth noting that we don't pass any props or utilize context within this component since there is no need to work with data at this level.

Step 5

In this step, we need to access the data in order to render the information about the planets. To do this, we will follow these steps:

Import the Context from the context.js file.

Use the useContext hook to retrieve the planets data from the context.

Render the markup using the map function, which allows us to iterate over the data set in React. Apply destructuring to access all the properties of each planet object.

Full code of the PlanetItem.jsx file after the step five.

Full app code:

Please take a moment to review the entire project, paying attention to the overall functionality and structure. For now, it is suggested to focus on understanding how the data is passed and rendered in the different components. Note how the data is obtained and utilized in the child components, excluding the Filter component. The Filter component will be a challenge in the next chapter, so you can further enhance the app's functionality.

Everything was clear?

Section 3. Chapter 11