Current section: Optimize Context 33 exercises
lesson

Intro to Optimize Context

Loading lesson

Transcript

00:00 There are a couple of things that we can do to optimize context, and we're going to explore those in this exercise. The basic idea is when the context provider gets re-rendered, all of the consumers of the context provider value will also re-render. But that's not entirely the case.

00:18 You can optimize that a little bit so that only when the value changes will the consumers be re-rendered. We can prevent the context provider itself from being re-rendered unnecessarily. That's what we're going to be exploring in this exercise.

00:34 The biggest unique aspects of this, there are two big unique aspects of this, and that is one, finding a way to preserve the identity of the value, so that even if this provider component does get re-rendered, it only re-renders consumers if the value changes. We'll use UseMemo for that.

00:53 Then also, it's definitely a fringe or edge case scenario where you'd want to do this, but you can actually have two different contexts. One context that provides the state value, and another context that provides the updater value.

01:13 That way, if you have some components that only care about updating the state and other components that care about the state itself or both, the ones who only care about updating the state won't need to re-render because they're consuming the separate context that just consumes the updater.

01:31 That's what we're going to be exploring in this exercise. It is definitely an edge scenario. There aren't very many scenarios that I've seen where you have components that only care about updating the value, and you have enough of those that it actually makes sense to split the context. But I want to show it to you anyway,

01:50 so that you just have another tool in your tool belt. That's what we're going to be exploring in this exercise of optimizing context. Let's get to it.