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](bit.ly/reactsnippet) 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

 
0
Kudos
 
0
Kudos

Now read this

Today I Learnt Some HTML.

Total Days 2 Total Earned $0. I learnt that a “tag” is a bit of code that tell a browser what to do. For a tag to work you have to <open> it and then </close> it. If you want some text on a webpage you put it inside a... Continue →