React Class or Function Components?
There are two ways to write React Components: the older Class Component and the newer recommended( Function Component ), but what’s the difference?
In this article we will give a general overview of Class and Function Components.
Overview
React is an open-source JavaScript library created by Facebook that has a large and active community and a rich ecosystem of tools and resources.
React allows developers to create reusable UI Components to build complex and interactive applications. It can be used on both the client-side and server-side, and can easily be integrated with other libraries and frameworks.
React has grown a lot in popularity over the past few years and it’s one of the most go-to libraries for developers due to its numerous advantages for creating user-friendly web applications.
The library is known also for its good performance, scalability, development speed, and a large community that supports the library and users.
Class vs Function
Being a Component library, React knows how to handle and encapsulate Components that manage their own states and join them to create UIs.
A Component in React can be written as a JavaScript class that extends React.Component
or React.PureComponent
and provides features such as state management and lifecycle methods.
Class Components have some methods such as componentDidMount
or componentDidUpdate
to handle the Component lifecycle, constructor
to initialize an instance, and functionalities like context
or refs
.
Components in React can be written as functions. They accept a set of props as input and return a React element as output.
Version 16.8 of React brought a huge change to Function Components with the introduction of React Hooks, which allows developers to manipulate state and Component lifecycle methods, and manipulate context
or refs
just like a Class Component.
Props
React Components often include the use of props
. Props (short for “properties”) is read-only data passed to a component by its parent.
They are used to customize and configure a Component with specific data. Props are accessed using the function’s first parameter, which is a JavaScript Object and is called props
in the community.
We can think of props as arguments for a function.
Using props in a Function Component:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Using props in a Class Component.:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Re-using the Component and passing props will work the same way independent of how the Component was written.
<Welcome name={"Henrique"} lastName={"Medeiros"} />
Passing “Henrique” as the name
prop here, it’s like passing an argument to a function. The primary distinction between props and function arguments is that if we provide an additional prop called lastName to our
Instead, it will be passed as an extra key-value pair in the first parameter’s object.
State
Another well-known feature that React offers is state
manipulation. State can be defined as the Component memory representing the internal data of a Component.
It’s used to manage data that can change over time, such as user input, network requests, state of the UI or even methods. State is clearer to understand since the declared name speak for itself. This is what you will find in that current time for your Component.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
render() {
return <h2>It is {this.state.date.toLocaleTimeString()}.</h2>;
}
}
Handling state in a Class Component.
function Clock(props) {
const [date, setDate] = useState(new Date());
return <h2>It is {date.toLocaleTimeString()}.</h2>;
}
Handling state in a Function Component.
There are several ways to initialize the state in the Class Components. This example shows initialization in the constructor
method.
The Function Component, on the other hand, uses useState
which is a Hook.
Hooks
Hooks are a technique that allows you to use state, synchronization with the DOM and other features. Hooks, like functions, were made so they can be used in Function Components. They won’t work in Class Components.
After its introduction, React Hooks quickly become a popular feature of the library and they are now the recommended way of writing Components. They enable developers to create reusable logic that can be shared across Components.
One of the most commonly used hooks is the useState
hook, which allows you to add state to Components.
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Click me
</button>
</div>
);
}
Another important hook is the useEffect
hook, which allows you to synchronize with the DOM in Function Components just like in Class Components’ lifecycle methods.
function Example() {
const [count, setCount] = useState(0);
const [tooManyClicks, setTooManyClicks] = useState(false);
useEffect(() => {
console.log('Component "mounted". Mimics ComponentDidMount callback');
return () => {
console.log('Component "unmounted". Mimics ComponentWillUnmount callback');
}
}, []);
useEffect(() => {
console.log('Component updated. Mimics ComponentWillUpdate callback');
setTooManyClicks(count > 10)
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
{tooManyClicks && <p>You are clicking too many times, stop!</p>}
</div>
);
}
Other built-in Hooks will appear within the library, they are very useful to make the UI behavior fit your requirements.
A plus that Hooks give developers is making your own Custom Hooks , with them you can create hooks to re-use logic between Components. Custom Hooks can also be shared as a package through npm
or yarn
.
Hooks don’t cover all use cases for Class Components yet, according to React docs FAQ: ‘There are no Hook equivalents to the uncommon getSnapshotBeforeUpdate
, getDerivedStateFromError
and componentDidCatch
life-cycles yet, but we plan to add them soon.’
Class or Function Components?
Both Class and Function Components can manipulate state and provide methods to keep your Component up to date with the latest changes and to perform operations during React lifecycle stages.
Function Components have become more popular due to their simplicity and better performance, and React recommends developing your application using them.
Function Components are generally considered easier to read and write because they have less boilerplate code compared to Class Components. They are also easier to test and optimize.
When using Function Components you will be using React Hooks, which provide a simpler and more efficient way to manage state in the Component and across other Components or manipulate Component lifecycle methods.
However, there are some cases where Class Components may still be necessary, such as when working with legacy code or when using certain third-party libraries that require Class Components. But in general, you will want to use Function Components to create new React Components.
Did you know that we build React applications? Checkout a case study we did about building a React application for Snapchat .