React Component Defaults

I’m giving up stateless functional components for a while.

They’re super nice but they’re not worth the refactor when you need a lifecycle method.

You could use recompose, which is also super nice, but completely avoidable.

Sticking to Class Components and I won’t need recompose or a refactor.

If I’m going with Class Components then I might as well go with Pure Class Components.

React.PureComponent stops components from needlessly re-rendering. PureComponent is not something you use on a special occasion, it’s a sensible default.

The only reason I’d need to use a regular class component is when I want the component to re-render when a nested prop or value in state changes.

Then its back to React.Component and a shouldComponentUpdate(). A regular component without a shouldComponentUpdate method is now a red flag for me.

I used [Pawel’s amzong snippet generator]( to create my new go-to VS Code snippet:

"Sensible Default Component": {
        "prefix": "rdc",
        "body": [
            "import React, { PureComponent } from 'react';",
            "import PropTypes from 'prop-types';",
            "class ${1:ComponentName} extends PureComponent {",
            "  static propTypes = {};",
            "  render() {",
            "    return (",
            "      <div>",
            "          <p>hello</p>",",
            "      </div>",
            "    );",
            "  }",
            "export default ${1:ComponentName};"
        "description": "React class component with senible defaults"

Another sensible default is using Strict Mode. You can enable <React.StrictMode> in any part of your application and you get a bunch of helpful warnings. Now I wrap my root component in a set of strict mode tags.

Learning Log Stats


Now read this

React setState takes an updater function

If you increment a count in state using a state update function 3 times then the final count will be 3. state = {count: 0} this.setState( previousState => ({count: previousState.count++})) this.setState( previousState => ({count:... Continue →