- empowers functional components
- an alternative to using Redux
- allows you to avoid “props-drilling”, which means that if you have a deep nesting of your components, you won’t have to pass the props all that way down
Context is well explained in the official React documentation, so I decided to go with rather a practical example.
Hooks API Reference - React
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. This…
Context - React
Context provides a way to pass data through the component tree without having to pass props down manually at every…
Source Code Files Structure
- welcome.component, which is basically a main page.
- library.component — an empty component created solely for demonstration purposes.
- containers/app-layout.component has a purpose of ‘structuring’ the components and solves the following issue:
- state/url.context.ts is our context
- hooks/url.hook.ts — updates the url context
So, I have a particular use case scenario for the useContext (screenshots below illustrate already working solution):
- My header has breadcrumbs, that show which page the user is currently viewing.
- When I click on the Library button, the route will update to /library and I show it in the navbar as a breadcrumb.
Create your Context
In my case, I called it urlContext, and it will store the url value, which it receives from React Router match.
Create a Setter to update your Context’s state
- create a useUrl hook, which stores the state of the context, as well as updates it.
- we will create a setCurrentUrl setter method to update the state from within a child component.
We have our routes wrapped into urlContext.Provider, which provides the context to the components it wraps.
Set Up Your Routes
Update Your Context
So, the idea is that when I am visiting the library page, my route obviously changed to /library, the context state is updated and the change is reflected in my header component.
matchobject contains information about how a
<Route path>matched the URL.
matchobjects contain the following properties:
url- (string) The matched portion of the URL. Useful for building nested
- Now what we’re going to do is use setCurrentUrl setter to update the context state with the value of match.url
- After we created our context and wrapped around our components, our AppLayout component will consume its value.
The screenshot above has our Header component nested inside the AppLayout component, and our parent component also contains our routes (/library and /welcome)as its children.
And as you can see, we import our urlContext, destructure it, and pass the url as a prop to our Header so that it can use it, right.
The last part is easy now, we just render the prop where we want inside the header, in my case it acts as a breadcrumb.
💻 The source code can be found here
That’s all Folks! ☕️