Skip to content

Instantly share code, notes, and snippets.

@busticated
Created Jan 11, 2018
Embed
What would you like to do?
React Context + GatsbyJS
// src/components/Foo.js
import createClass from 'create-react-class';
import { div, em } from 'react-dom-factories';
import PropTypes from 'prop-types';
export default createClass({
displayName: 'Foo',
contextTypes: {
count: PropTypes.number
},
render(){
const { count } = this.context;
return div(null,
em(null, `COMPONENT COUNT: ${count}`),
);
}
});
// src/layouts/index.js
import { createElement } from 'react';
import createClass from 'create-react-class';
import { div, h1 } from 'react-dom-factories';
import PropTypes from 'prop-types';
import Foo from '../components/Foo';
export default createClass({
displayName: 'TestLayout',
propTypes: {
children: PropTypes.func
},
childContextTypes: {
count: PropTypes.number
},
getChildContext(){
return {
count: this.state.count
};
},
getInitialState(){
return { count: 0 };
},
componentDidMount(){
(function run(self){
self.setState({ count: self.state.count += 1 });
self._timer = setTimeout(run, 1000, self);
}(this));
},
componentWillUnmount(){
if (this._timer){
clearTimeout(this._timer);
}
},
render(){
const { count } = this.state;
const { children } = this.props;
return div(null,
h1(null, `COUNT: ${count}`),
createElement(Foo),
children()
);
}
});
// src/pages/test.js
import createClass from 'create-react-class';
import { div, p } from 'react-dom-factories';
import PropTypes from 'prop-types';
export default createClass({
displayName: 'TestPage',
contextTypes: {
count: PropTypes.number
},
render(){
const { count } = this.context;
return div(null,
p(null, `PAGE COUNT: ${count}`),
);
}
});
@busticated
Copy link
Author

busticated commented Jan 11, 2018

since Gatsby's internal component renderer calls shouldComponentUpdate() without checking for context changes, page updates are blocked.

screenshots:
screen shot 2018-01-11 at 11 42 32 am
screen shot 2018-01-11 at 11 42 48 am

@bzhr
Copy link

bzhr commented Mar 23, 2018

This is just an example that context doesn't work in Gatsby, itn't a solution, right? I used a starter that uses context (gatsby-firebase-starter) where the author didn't know context doesn't work in Gatsby. He has another example of the app as a plain React app using React v16.1 where context does work. I thought that if I use the gatsby-react-next that it will allow for use of context, just by including the plugin, but not really...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment