Frontend Developers: I'm redesigning DevTools. Want early access?

How to update React Context inside your child components

When I’m using React Context, I’ll occasionally need a way to update Context from inside a child component. This post outlines a simple and easy way to handle this. Also, if you’re just getting started with Context, you may want to read my setup guide instead.

1. Add a method called updateState to your provider, which simply calls this.setState. Then, attach it to your state:

// DataProvider.jsx

import React, { Component } from 'react'
import DataContext from 'path/to/your/DataContext'

class DataProvider extends Component {
	constructor(props) {
		super(props)
		this.updateState = this.updateState.bind(this) // ← Here
		this.state = {
			foobar: '...'
			update: this.updateState // ← Here
		}
	}

	updateState(values) { // ← And here
		this.setState(values)
	}

	render() {
		return (
			<DataContext.Provider value={this.state}>
				{this.props.children}
			</DataContext.Provider>
		)
	}
}

export default DataProvider

2. Now, inside the child component, you can use this.context.update to update the state. It works exactly like this.setState, so you can simply pass it a key: value pair.

// Grandchild.jsx

import React, { Component } from 'react'
import DataContext from 'path/to/your/DataContext'

class Grandchild extends Component {
	componentDidMount() {
		this.context.update({ foobar: 'It worked!' }) // ← Here
	}

	render() {
		return <div>{this.context.foobar}</div>
	}
}

Grandchild.contextType = DataContext

export default Grandchild

That’s all there is to it: you’ve updated a React component’s state from inside a child component via Context. If you need more guidance, I recommend reading my guide on setting up React Context.

Frontend Developers: I'm redesigning DevTools. Want early access?