-
Notifications
You must be signed in to change notification settings - Fork 19
Functional vs Class Components
In general, we should favor function-based components that use React Hooks as needed rather than traditional class-based components. While there is nothing inherently wrong with class-based components (and there are no plans to do away with them), functional components tend to be more concise and help lead us to smaller, function-specific files.
In the past, one had to choose class-based components if one needed to maintain state, perform side effects, or access shared context. Those restrictions no longer apply with the introduction of React Hooks.
Instead of:
import React from 'react';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
We can write the same as a more concise functional component using the useState
hook:
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In addition to the useState hook, you can utilize the useEffect hook to perform side effects (such as performing API requests, etc). The useEffect
hook in large part performs the roles of the componentDidMount
, componentDidUpdate
, and componentWillUnmount
lifecycle methods of class components.
Hooks can also be used for both React Router and React Redux.