Skip to content

Instantly share code, notes, and snippets.

@alexeyraspopov
Created October 27, 2018 05:44
Show Gist options
  • Save alexeyraspopov/2702114ec16794f63ec9c862c995a3dd to your computer and use it in GitHub Desktop.
Save alexeyraspopov/2702114ec16794f63ec9c862c995a3dd to your computer and use it in GitHub Desktop.

Stateful Class Components vs Function Components With Hooks

This is a quick comparison of a resulting code when using class components and function components with hooks.

The comparison shows the advantage of using hooks for the sake of not only DX but UX — less code to ship.

Testing components code can be found below. Babel was used for building and minifying the code. We compare ES5 and ES6 version (bundled for old browsers and new, using preset-env).

ES5

Class Component Function Component Difference
min 2229B 927B -58.41%
min+gzip 897B 524B -41.58%

ES6

Class Component Function Component Difference
min 524B 349B -33.39%
min+gzip 295B 230B -22.03%
import React from 'react';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
this.increment = this.increment.bind(this);
}
increment() {
this.setState(state => ({ counter: this.state.counter + 1 }));
}
render() {
return (
<section>
<p>{this.state.counter}</p>
<button onClick={this.increment}>+</button>
</section>
);
}
}
import React from 'react';
function Counter() {
let [counter, setCounter] = React.useState(0);
let increment = () => setCounter(counter + 1);
return (
<section>
<p>{counter}</p>
<button onClick={increment}>+</button>
</section>
);
}
{
"name": "hooks-numbers",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@babel/cli": "^7.1.2",
"@babel/core": "^7.1.2",
"@babel/preset-env": "^7.1.0",
"@babel/preset-react": "^7.0.0",
"babel-minify": "^0.5.0"
},
"scripts": {
"build": "babel *.js -d build",
"minify": "minify build/*.js -d build",
"gzip": "gzip build/*.js --keep --force",
"start": "npm run build; npm run minify; npm run gzip"
},
"browserslist": ["last 1 chrome version"],
"babel": {
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment