React useContext: How to Update Context from Child Component

theUnknown
4 min readOct 5, 2019

Why useContext

  • 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.

Source Code Files Structure

source code files structure
  • header.component
  • 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):

/welcome route
  • 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.
/library route

Create your Context

theUnknown

Everything is unknown until it’s known. Self-learner.

Recommended from Medium

Lists

See more recommendations