How to use React Context effectively

In Application State Management with React, I talk about how using a mix of local state and React Context can help you manage state well in any React application. I showed some examples and I want to call out a few things about those examples and how you can create React context consumers effectively so you avoid some problems and improve the developer experience and maintainability of the context objects you create for your application and/or libraries.

Please do read Application State Management with React and follow the advice that you shouldn\’t be reaching for context to solve every state sharing problem that crosses your desk. But when you do need to reach for context, hopefully this blog post will help you know how to do so effectively. Also, remember that context does NOT have to be global to the whole app, but can be applied to one part of your tree and you can (and probably should) have multiple logically separated contexts in your app.

First, let\’s create a file at src/count-context.js and we\’ll create our context there:

import * as React from \'react\'

const CountContext = React.createContext()

First off, I don\’t have an initial value for the CountContext. If I wanted an initial value, I would call React.createContext({count: 0}). But I don\’t include a default value and that\’s intentional. The defaultValue is only useful in a situation like this:

function CountDisplay() {
  const {count} = React.useContext(CountContext)
  return <div>{count}</div>
}

ReactDOM.render(<CountDisplay />, document.getElementById(\'⚛️\'))

Because we don\’t have a default value for our CountContext, we\’ll get an error on the highlighted line where we\’re destructuring the return value of useContext. This is because our default value is undefined and you cannot destructure undefined.

None of us likes runtime errors, so your knee-jerk reaction may be to add a default value to avoid the runtime error. However, what use would the context be if it didn\’t have an actual value? If it\’s just using the default value that\’s been provided, then it can\’t really do much good. 99% of the time that you\’re going to be creating and using context in your application, you want your context consumers (those using useContext) to be rendered within a provider which can provide a useful value.

Scroll to Top