Reader small image

You're reading from  Learn React Hooks

Product typeBook
Published inOct 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781838641443
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Daniel Bugl
Daniel Bugl
author image
Daniel Bugl

Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.
Read more about Daniel Bugl

Right arrow

Implementing React Context

In the previous chapters, we learned about the most fundamental Hooks, such as the State Hook, the Reducer Hook, and the Effect Hook. We developed a small blog application using these Hooks. We have noticed during the development of our blog app, that we have to pass down the user state from the App component to the UserBar component, and from the UserBar component to the Login, Register, and Logout components. To avoid having to pass down the state like this, we are now going to learn about React context and Context Hooks.

We are going to begin by learning what React context is, and what providers and consumers are. Then, we are going to use Context Hooks as a context consumer, and discuss when context should be used. Finally, we are going to implement themes and global state via contexts.

The following topics will be covered in this chapter:

  • Introducing...

Technical requirements

A fairly recent version of Node.js should already be installed (v11.12.0 or higher). The npm package manager for Node.js also needs to be installed.

The code for this chapter can be found on the GitHub repository: hhttps://github.com/PacktPublishing/Learn-React-Hooks/tree/master/Chapter05

Check out the following video to see the code in action:

http://bit.ly/2Mm9yoC

Please note that it is highly recommended that you write the code on your own. Do not simply run the code examples that have been provided. It is important that you write the code yourself in order for you to be able to learn and understand properly. However, if you run into any issues, you can always refer to the code example.

Now, let's get started with the chapter.

Introducing React context

In the previous chapters, we passed down the user state and dispatch function from the App component, to the UserBar component; and then from the UserBar component to the Logout, Login, and Register components. React context provides a solution to this cumbersome way of passing down props over multiple levels of components, by allowing us to share values between components, without having to explicitly pass them down via props. As we are going to see, React context is perfect for sharing values across the whole application.

First, we are going to have a closer look at the problem of passing down props. Then, we are going to introduce React context as a solution to the problem.

Passing down props

Before...

Implementing themes

After learning how to implement themes in a small example, we are now going to implement themes in our blog app, using React context and Hooks.

Defining the context

First, we have to define the context. Instead of defining it in the src/App.js file, in our blog app, we are going to create a separate file for the context. Having a separate file for contexts makes it easier to maintain them later on. Furthermore, we always know where to import the contexts from, because it is clear from the filename.

Let's start defining a theme context:

  1. Create a new src/contexts.js file.
  2. Then, we import React:
import React from 'react'
  1. Next, we define the ThemeContext. As before in our small example, we...

Using context for global state

After learning how to use React context to implement themes in our blog app, we are now going to use a context to avoid having to manually pass down the state and dispatch props for our global app state.

Defining StateContext

We start by defining the context in our src/contexts.js file.

In src/contexts.js, we define the StateContext, which is going to store the state value and the dispatch function:

export const StateContext = React.createContext({
state: {},
dispatch: () => {}
})

We initialized the state value as an empty object, and the dispatch function as an empty function, which will be used when no provider is defined.

...

Summary

In this chapter, we first learned about React context as an alternative to passing down props over multiple levels of React components. We then learned about context providers and consumers, and the new way to define consumers, via Hooks. Next, we learned when it does not make sense to use contexts, and when we should use inversion of control instead. Then, we used what we learned in practice, by implementing themes in our blog app. Finally, we used React context for the global state in our blog app.

In the next chapter, we are going to learn how to request data from a server, using React and Hooks. Then, we are going to learn about React.memo to prevent unnecessary re-rendering of components, and React Suspense to lazily load components when they are needed.

Questions

In order to recap what we have learned in this chapter, try to answer the following questions:

  1. Which problem do contexts avoid?
  2. What are the two parts that contexts consist of?
  3. Are both parts required to be defined in order to use contexts?
  4. What is the advantage of using Hooks, instead of traditional context consumers?
  5. What is an alternative to contexts, and when should we use it?
  6. How can we implement dynamically changing contexts?
  7. When does it make sense to use contexts for state?

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React Hooks
Published in: Oct 2019Publisher: PacktISBN-13: 9781838641443
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Daniel Bugl

Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.
Read more about Daniel Bugl