Skip to content

Commit

Permalink
Warn about readContext() during class render-phase setState()
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon committed Jan 23, 2019
1 parent 933ca3c commit d1d4dda
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
15 changes: 14 additions & 1 deletion packages/react-reconciler/src/ReactUpdateQueue.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ import type {Fiber} from './ReactFiber';
import type {ExpirationTime} from './ReactFiberExpirationTime';

import {NoWork} from './ReactFiberExpirationTime';
import {
stashContextDependenciesInDEV,
unstashContextDependenciesInDEV,
} from './ReactFiberNewContext';
import {Callback, ShouldCapture, DidCapture} from 'shared/ReactSideEffectTags';
import {ClassComponent} from 'shared/ReactWorkTags';

Expand Down Expand Up @@ -348,6 +352,7 @@ function getStateFromUpdate<State>(
if (typeof payload === 'function') {
// Updater function
if (__DEV__) {
stashContextDependenciesInDEV();
if (
debugRenderPhaseSideEffects ||
(debugRenderPhaseSideEffectsForStrictMode &&
Expand All @@ -356,7 +361,11 @@ function getStateFromUpdate<State>(
payload.call(instance, prevState, nextProps);
}
}
return payload.call(instance, prevState, nextProps);
const nextState = payload.call(instance, prevState, nextProps);
if (__DEV__) {
unstashContextDependenciesInDEV();
}
return nextState;
}
// State object
return payload;
Expand All @@ -372,6 +381,7 @@ function getStateFromUpdate<State>(
if (typeof payload === 'function') {
// Updater function
if (__DEV__) {
stashContextDependenciesInDEV();
if (
debugRenderPhaseSideEffects ||
(debugRenderPhaseSideEffectsForStrictMode &&
Expand All @@ -381,6 +391,9 @@ function getStateFromUpdate<State>(
}
}
partialState = payload.call(instance, prevState, nextProps);
if (__DEV__) {
unstashContextDependenciesInDEV();
}
} else {
// Partial state object
partialState = payload;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1347,6 +1347,31 @@ describe('ReactNewContext', () => {
expect(ReactNoop.flush()).toEqual(['App', 'App#renderConsumer']);
expect(ReactNoop.getChildren()).toEqual([span('goodbye')]);
});

it('warns when reading context inside render phase class setState updater', () => {
const ThemeContext = React.createContext('light');

class Cls extends React.Component {
state = {};
render() {
this.setState(() => {
readContext(ThemeContext);
});
return null;
}
}

ReactNoop.render(<Cls />);
expect(ReactNoop.flush).toWarnDev(
[
'Context can only be read while React is rendering',
'Cannot update during an existing state transition',
],
{
withoutStack: 1,
},
);
});
});

describe('useContext', () => {
Expand Down

0 comments on commit d1d4dda

Please sign in to comment.