React from prop drilling to use hook to pass data in app

Nguyen Cao Phung
Nov 8 · 3 min read

Goal: In this article I’ll walk you through props drilling problem in a typical React application to use hook `useContext` to pass data, function in an application

Prop drilling in typical React application.

Take a look a simple example of shopping page that let user add item from list and the number of item will be displayed on cart. The number of items will be passed top-down from parent component, here is Page to Cart` component.

Demo:

Use context to avoid props drilling

To avoid prop drilling problem, we use Context. Context provide a way for easy sharing data between components. In the example, say we need to add Checkout button at the bottom of list that need display total price of items. (for simple, I use number of items only for demo). You pass data to Provider then Provider can pass data to Consumer directly without tree level.

Demo

https://codesandbox.io/embed/react-context-ooh65?fontsize=14

Updating Context from a Nested Component

Above steps just show you how to pass data from Provider to Consumer, to update data you still need action up from Add button. What if you want to update data from Add button without design action up? We can pass setCart function down through the context to allow Add button update cart data.

Demo

https://codesandbox.io/s/react-context-allow-consumer-update-context-4qhn1?fontsize=14

Some time you don’t want re-render Page, you can move state out of Page

Page contain cart data (state), then Page is re-rendered when cart is updated. Some case, you don’t want data updating cause re-render Page, you can make CartProvider component to contain cart data instead of Page.

Demo

https://codesandbox.io/s/react-context-move-state-out-of-page-provider-hoc-6joqn?fontsize=14

Use `useContext` to make custom hook useCart`

If you don’t want to use CartContext.Consumer wrapper, you can use hook

Demo

https://codesandbox.io/s/react-context-use-hook-99egn?fontsize=14

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade