Skip to content

Instantly share code, notes, and snippets.

@Rendez
Last active July 11, 2018 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rendez/b6e7834de37cce367e2cf8b718ec8bc3 to your computer and use it in GitHub Desktop.
Save Rendez/b6e7834de37cce367e2cf8b718ec8bc3 to your computer and use it in GitHub Desktop.
SSR-safe React Component
const unexpectedLifecycleMethods = ['componentDidMount', 'componentDidUpdate', 'componentWillUpdate', 'UNSAFE_componentWillUpdate', 'componentShouldReceiveProps', 'UNSAFE_componentShouldReceiveProps'];
class SSRComponent extends React.Component {
constructor(...args) {
super(...args);
unexpectedLifecycleMethods.forEach((methodName) => {
if (this.hasOwnProperty(methodName)) {
throw new Error(`Cannot declare '${methodName}' in a server-side-rendered component`);
}
});
}
setState() {
throw new Error('Cannot set state in a server-side-rendered component');
}
forceUpdate() {
throw new Error('Cannot update in a server-side-rendered component');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment