Avoid Prop Drilling using Context in React

Paul McBride
InstructorPaul McBride
Share this video with your friends

Social Share Links

Send Tweet

A common struggle with building React apps is having to pass props through a deeply nested component tree. In this lesson you'll learn how to avoid prop drilling using the useContext hook.

Paul McBride: [00:00] Here's an app made up of three separate components. At the top level, we have this app component that contains some state and a few functions for updating that state.

[00:09] It renders out the CountTitle component and passes the count as a prop. In the CountTitle component, we render out an H1, and it renders the CountNumber component and passes count through as a prop again.

[00:22] Finally, if we look at the CountNumber component, it renders a span and renders the count directly into the DOM here. If we click increase count, the number goes up, and then we can reset it back to zero.

[00:33] Now, one of the things you'll notice is that we're passing the count prop through to CountTitle, which doesn't actually use it, and passes it on to the CountNumber component.

[00:43] In this trivial app, that prop drilling isn't really a problem. In a much deeper tree, that could start to become really inconvenient. Let's tackle this using context.

[00:52] The first thing I'm going to do is create a new context object. Now, this createContext function can take an optional default value, but here, we're going to leave it blank.

[01:03] The next thing we need to do is take this CountContext and wrap our app in a context provider. I'm going to scroll down to our app component, and we're going to paste in CountContext.provider. Then we'll move the rest of our app inside that.

[01:20] The context provider expects a value prop. In this case, we're passing through count in an object. Now, let's scroll back up to our CountNumber component and figure out how to use this.

[01:32] We'll start by importing useContext. Then in the CountNumber component, we're going to create a new variable, count, which we will de-structure from the results of useContext. We'll pass the CountContext in as an argument.

[01:47] Now, we're running into an error here because the count variable duplicated, so let's remove it from this function, and everything should work as it did before. If we increase the count or reset the count, everything works.

[01:59] We can now go to our CountTitle and remove all references to count, as it no longer needs it. Then let's do the same in the app component where we render CountTitle. One thing to note is that every time the value prop passed to a context provider changes, all of its children re-render.

[02:19] Now here, we're passing an object as a value, and that object is re-created on every render. Every time state changes in this component, the entire tree re-renders. This can be avoided in a few different ways, but it's out of the scope of this video.