Skip to content

Context tweaks #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Mar 23, 2018
38 changes: 25 additions & 13 deletions content/docs/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,32 @@ Context provides a way to pass data through the component tree without having to

In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like this between components without having to explicitly pass a prop through every level of the tree.

- [Motivation](#motivation)
- [When to Use Context](#when-to-use-context)
- [API](#api)
- [React.createContext](#reactcreatecontext)
- [Provider](#provider)
- [Consumer](#consumer)
- [Examples](#examples)
- [Static Context](#static-context)
- [Dynamic Context](#dynamic-context)
- [Consuming Multiple Contexts](#consuming-multiple-contexts)
- [Accessing Context in Lifecycle Methods](#accessing-context-in-lifecycle-methods)
- [Forwarding Refs to Context Consumers](#forwarding-refs-to-context-consumers)
- [Legacy API](#legacy-api)


## Motivation
## When to Use Context

Context is designed to relieve the pain of passing props down through a deeply nested component tree. For example, in the code below we manually thread through a color prop in order to style the Button and Message components:
Context is designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a "theme" prop in order to style the Button component:

`embed:context/motivation-problem.js`

Using context, we can avoid passing props through intermediate elements:

`embed:context/motivation-solution.js`

Note: Don't use context just to avoid passing props a few levels down. Stick to cases where the same data needs to accessed in many components at multiple levels.

## API

### `React.createContext`
Expand All @@ -55,26 +60,20 @@ Accepts a `value` prop to be passed to Consumers that are descendants of this Pr

```js
<Consumer>
{ value => { /* render something based on the context value */ } }
{value => /* render something based on the context value */}
</Consumer>
```

A React component that subscribes to context changes.

Requires a [function as a child](/docs/render-props.html#using-props-other-than-render). This function receives the current context value and returns a React node. It will be called whenever the Provider's value is updated.
Requires a [function as a child](/docs/render-props.html#using-props-other-than-render). The function receives the current context value and returns a React node. All consumers are re-rendered whenever the Provider value changes. Changes are determined by comparing the new and old values using [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).

> Note:
>
> For more information about this pattern, see [render props](/docs/render-props.html).

## Examples

### Static Context

Here is an example illustrating how you might inject a "theme" using context:

`embed:context/theme-example.js`

### Dynamic Context

A more complex example with dynamic values for the theme:
Expand All @@ -88,8 +87,21 @@ A more complex example with dynamic values for the theme:
**app.js**
`embed:context/theme-detailed-app.js`

## Consuming Multiple Contexts

`embed:context/multiple-contexts.js`

## Accessing Context in Lifecycle Methods

`embed:context/lifecycles.js`

## Forwarding Refs to Context Consumers

`embed:context/forwarding-refs.js`

## Legacy API

> The legacy context API was deprecated in React 16.3 and will be removed in version 17.
> Note:
>
> React previously shipped with an experimental context API. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. Read the [legacy context docs here](/docs/legacy-context.html).
> React previously shipped with an experimental context API. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. The legacy API will be removed in React 17. Read the [legacy context docs here](/docs/legacy-context.html).

14 changes: 7 additions & 7 deletions content/docs/legacy-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ title: Legacy Context
permalink: docs/legacy-context.html
---

> Deprecation Warning
> Note:
>
> The legacy API has been deprecated and will be removed in version 17.
> The legacy context API will be removed in version 17.
> Use the [new context API](/docs/context.html) introduced with version 16.3.
> The legacy API will continue working for all 16.x releases.

## How To Use Context

> This section documents a deprecated API. See the [new API](/docs/context.html).
> This section documents a legacy API. See the [new API](/docs/context.html).

Suppose you have a structure like:

Expand Down Expand Up @@ -107,7 +107,7 @@ If `contextTypes` is not defined, then `context` will be an empty object.

### Parent-Child Coupling

> This section documents a deprecated API. See the [new API](/docs/context.html).
> This section documents a legacy API. See the [new API](/docs/context.html).

Context can also let you build an API where parents and children communicate. For example, one library that works this way is [React Router V4](https://reacttraining.com/react-router):

Expand Down Expand Up @@ -139,7 +139,7 @@ Before you build components with an API similar to this, consider if there are c

### Referencing Context in Lifecycle Methods

> This section documents a deprecated API. See the [new API](/docs/context.html).
> This section documents a legacy API. See the [new API](/docs/context.html).

If `contextTypes` is defined within a component, the following [lifecycle methods](/docs/react-component.html#the-component-lifecycle) will receive an additional parameter, the `context` object:

Expand All @@ -154,7 +154,7 @@ If `contextTypes` is defined within a component, the following [lifecycle method

### Referencing Context in Stateless Functional Components

> This section documents a deprecated API. See the [new API](/docs/context.html).
> This section documents a legacy API. See the [new API](/docs/context.html).

Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows a `Button` component written as a stateless functional component.

Expand All @@ -171,7 +171,7 @@ Button.contextTypes = {color: PropTypes.string};

### Updating Context

> This section documents a deprecated API. See the [new API](/docs/context.html).
> This section documents a legacy API. See the [new API](/docs/context.html).

Don't do it.

Expand Down
12 changes: 12 additions & 0 deletions examples/context/forwarding-refs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const Button = ({theme, children}) => (
<button className={theme ? 'dark' : 'light'}>
{children}
</button>
);

// highlight-range{1,3}
export default React.forwardRef((props, ref) => (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} ref={ref} />}
</ThemeContext.Consumer>
));
22 changes: 22 additions & 0 deletions examples/context/lifecycles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Button extends React.Component {
componentDidMount() {
// highlight-next-line
alert(this.props.theme);
}

render() {
const {theme, children} = this.props;
return (
<button className={theme ? 'dark' : 'light'}>
{children}
</button>
);
}
}

// highlight-range{3}
export default props => (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} />}
</ThemeContext.Consumer>
);
47 changes: 18 additions & 29 deletions examples/context/motivation-problem.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,23 @@
class Button extends React.Component {
render() {
return (
<button style={{background: this.props.color}}>
{this.props.children}
</button>
);
}
}
const ThemedButton = props => {
//highlight-range{1}
return <Button theme={props.theme} />;
};

class Message extends React.Component {
render() {
// highlight-range{1-3}
// The Message component must take `color` as as prop to pass it
// to the Button. Using context, the Button could connect to the
// color context on its own.
return (
<div>
<p>{this.props.text}</p>
<Button color={this.props.color}>Delete</Button>
</div>
);
}
}
// An intermediate component
const Toolbar = props => {
// highlight-range{1-2,5}
// The Toolbar component must take an extra theme prop
// and pass it to the ThemedButton
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
};

class MessageList extends React.Component {
class App extends React.Component {
render() {
const color = 'purple';
const children = this.props.messages.map(message => (
<Message text={message.text} color={color} />
));
return <div>{children}</div>;
// highlight-range{1}
return <Toolbar theme="dark" />;
}
}
60 changes: 25 additions & 35 deletions examples/context/motivation-solution.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,33 @@
// highlight-range{1}
const ColorContext = React.createContext();
// Create a theme context, defaulting to light theme
// highlight-next-line
const ThemeContext = React.createContext('light');

class Button extends React.Component {
render() {
// highlight-range{2-8}
return (
<ColorContext.Consumer>
{color => (
<button style={{background: color}}>
{this.props.children}
</button>
)}
</ColorContext.Consumer>
);
}
}
const ThemedButton = props => {
// highlight-range{1,3-5}
// The ThemedButton receives the theme from context
return (
<ThemeContext.Consumer>
{theme => <Button theme={theme} />}
</ThemeContext.Consumer>
);
};

class Message extends React.Component {
render() {
return (
<div>
<p>{this.props.text}</p>
<Button>Delete</Button>
</div>
);
}
}
// An intermediate component
const Toolbar = props => {
return (
<div>
<ThemedButton />
</div>
);
};

class MessageList extends React.Component {
class App extends React.Component {
render() {
const color = 'purple';
const children = this.props.messages.map(message => (
<Message text={message.text} />
));
// highlight-range{2-4}
// highlight-range{2,4}
return (
<ColorContext.Provider value={color}>
{children}
</ColorContext.Provider>
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
38 changes: 38 additions & 0 deletions examples/context/multiple-contexts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Theme context, default to light theme
// highlight-next-line
const ThemeContext = React.createContext('light');

// Signed-in user context
// highlight-next-line
const UserContext = React.createContext();

class App extends React.Component {
static propTypes = {
theme: PropTypes.string,
signedInUser: PropTypes.shape({
id: number,
name: string,
avatar: string,
}),
};

render() {
// highlight-range{9}
return (
<ThemeContext.Provider value={this.props.theme}>
<UserContext.Provider
value={this.props.signedInUser}>
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<ProfilePage user={user} theme={theme} />
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>
</UserContext.Provider>
</ThemeContext.Provider>
);
}
}
28 changes: 22 additions & 6 deletions examples/context/theme-detailed-app.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import {ThemeContext, themes} from './theme-context';
import ThemedButton from './button';

// An intermediate component that uses the ThemedButton
const Toolbar = props => {
return (
<ThemedButton onClick={props.changeTheme}>
Change Theme
</ThemedButton>
);
};

class App extends React.Component {
state = {
theme: themes.light,
Expand All @@ -16,13 +25,20 @@ class App extends React.Component {
};

render() {
//highlight-range{2,6}
//highlight-range{1-3}
// The ThemedButton button inside the ThemeProvider
// uses the theme from state while the one outside uses
// the default dark theme
//highlight-range{3-5,7}
return (
<ThemeContext.Provider value={this.state.theme}>
<ThemedButton onClick={this.toggleTheme}>
Change Theme
</ThemedButton>
</ThemeContext.Provider>
<div>
<ThemeContext.Provider value={this.state.theme}>
<Toolbar changeTheme={this.toggleTheme} />
</ThemeContext.Provider>
<div>
<ThemedButton />
</div>
</div>
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/context/theme-detailed-theme-context.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ export const themes = {

// highlight-range{1-3}
export const ThemeContext = React.createContext(
themes.dark
themes.dark // default value
);
Loading