1. Introduction to React Fundamentals
2. Styling in React Apps
3. React Hooks and Context
Context 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:
PlanetItem. To visualize their hierarchy, please refer to the image below.
Context in the
context.js file at the top level.
Let the entire app know that we are using context. So, we need to wrap the whole app with the
Context.Provider in the
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
Initialize the state for the
planets as an empty array using 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
appData variable to the
value prop of the context provider.
Full code of the
App.jsx file after the step three.
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.
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:
Context from 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?