If you're learning React JS, you'll quickly encounter two ways of creating components: Function Components and Class Components. Both are valid, both work, and both have their place—although one is definitely more modern and widely recommended today.
In this casual article, let's explore the difference between function and class components, their pros and cons, when to use each, and answer the classic question: function vs class which one wins?
What Is a Component in React?
First things first—components are the building blocks of React applications. Think of them as LEGO bricks you can mix and match to build user interfaces. Components can be tiny (like a button) or massive (like an entire page).
Every component can have:
- UI (written in JSX)
- Logic (event handlers, state)
- Props (data from parent components)
And you can write them in two main styles:
- Function Components
- Class Components
Class Components
Class components are the older, traditional way to create components in React. They use JavaScript classes and are more verbose.
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Key characteristics:
- Use the
class
keyword and extendReact.Component
- Props and state are accessed with
this
- Require a
render()
method
Function Components
Function components are more modern and now the preferred way to write components in React.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// Or using arrow function:
const Welcome = ({ name }) => <h1>Hello, {name}</h1>;
Advantages: shorter, easier to read, no need for this
, and easy to reuse logic with Hooks.
Then Came Hooks
Before Hooks were introduced in React 16.8, function components were "dumb" they couldn't manage state or lifecycle logic. But with Hooks like useState
and useEffect
, function components became much more powerful and flexible.
Function vs Class: Side-by-Side Comparison
Aspect | Class Component | Function Component |
---|---|---|
Syntax | Uses class and this |
Plain JavaScript function |
Props | this.props |
props (or destructured) |
State | this.state , this.setState() |
useState() |
Lifecycle | componentDidMount , etc. |
useEffect() |
Binding | Often needed | Not required |
Code Length | More verbose | More concise |
Future-Proof | Still supported | Recommended going forward |
Example: Counter Component
Class Version
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>+1</button>
</div>
);
}
}
Function Version
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
};
Say Goodbye to this
One of the most painful parts of class components for beginners is dealing with this
. You often have to manually bind methods in the constructor. With function components, you don’t have to worry about this
at all. Simpler, cleaner, and less buggy!
Lifecycle Methods in One Hook
In class components, you’d use methods like:
componentDidMount()
componentDidUpdate()
componentWillUnmount()
In function components, you can handle all that with just one hook:
useEffect(() => {
console.log("Mounted");
return () => {
console.log("Unmounted");
};
}, []);
When Should You Still Use Class Components?
Although function components are preferred now, class components are still useful in some cases:
- Working with legacy code
- Some older libraries still rely on class lifecycle methods
- You’re refactoring old projects
Why Function Components Are the Future
React’s documentation and ecosystem are moving toward function components for good reason:
- Shorter, cleaner syntax
- Hooks make logic reusable
- Easier to test
- Better performance in some cases
Final Thoughts: Function Component Wins!
If you’re just starting with React, use function components. They’re simpler, more modern, and more aligned with where React is going. But if you want to be a well-rounded React developer, understanding class components will help you maintain or upgrade older projects.
Tips
- Use
useReducer()
for complex state management - Use
useCallback()
to prevent unnecessary renders - Use
useMemo()
for performance optimization
0 Comments:
Post a Comment