Here is an example from ReactConf2018 Dan Abramov's talk explaining the difference:
Here are the few findings from the below example:
- You'll writing less boilerplate code using hooks
- Accessing lifecycles updates and states updates with
useEffect()
- Regarding performace one aspect is:
Unlike componentDidMount and componentDidUpdate, the function passed to useEffect fires after layout and paint, during a deferred event
- Code sharing will too much easy and useEffect() can be implemented multiple times for different purposes within the same component.
- you can control component re render more efficiently by passing an array as second argument to
useEffect()
hook that is very effective when you just pass empty array [] to render component on only mounting and unmounting.
- Use Multiple
useEffect()
hooks to Separate Concerns and react will:
Hooks lets us split the code based on what it is doing rather than a lifecycle method name. React will apply every effect used by the component, in the order they were specified
Using Classes:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
Using Hooks:
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}