Current section: Shared Context 36 exercises
solution

Context Provider

Loading solution

Transcript

00:00 Alrighty, so let's start with the type that we need for our search params context So I'm going to do right type search params tuple It's a read-only array of the URL search params type and a type of the set global search params

00:17 This type is exactly the same as what we're returning from our use search params And this is going to be the value of our context So let's create our context our search params context, which will be the react create context of the search params Temple, let's get rid of the react dot here and pull in that import from react

00:35 And so now we've got our search params context That we can render for our app here So what we can do actually to make things pretty easy is instead of use search params right here

00:51 I'm going to copy that and we're going to call this our search search params provider And we'll accept children. That's our react node and then down here instead of returning this this is actually going to be our value and Then we can return

01:09 Our search params context our AI assistant wants to do dot provider You no longer need to do that. If you've been doing react for a while, you might have done that also But react doesn't require you to have the dot provider anymore. In fact, it's deprecated. So stop doing that

01:25 But we render our search params context. Here's our value and we'll render the children along with that and Now we'll create a use search params hook that simply returns use Use search params context will bring in use from react and

01:45 That it is going to make it all work all over the place except first We need to wrap everything in the search params provider so that they're all accessing The same params that are managed by the search params provider. So with that all done Now they're accessing the same params. And so therefore

02:06 We are updating the search for what's in the URL and we're also updating The params that are used to manage the sorting and the filtering of the blog posts So just quick review on this. We created a type for our context. We Initialized our context here

02:25 we updated our hook to instead be a provider that rendered our context and then we made our simple hook that consumes that context and then we wrap everything in our app with the Context provider so that all of the components that use our hook Will access the same context provider

02:46 So for example, this this is important because if I tried to do a matching post outside of here Now we're not going to have them using the same Context value. So that is your little intro to context