React Components: Class vs Functional.

RMAG news

My React journey began four years ago with functional components and Hooks. Then came ‘Siswe, a fellow participant in the bootcamp and our resident class component enthusiast. While the rest of us were collaborating on team projects with functional components, ‘Siswe clung to class components with an unwavering loyalty.

Components are the building blocks of your user interface (UI).

Think of them as Lego bricks – you can combine them in various ways to create complex structures. They are independent and reusable pieces of code that encapsulate UI and logic.

Reusing a component within another component typically looks like this:

import MyComponent from ‘./MyComponent’;

function ParentComponent() {
return (
<div>
<MyComponent />
</div>
);
}

Class Components and Functional Components are the two primary ways to create components in React.

import React, { Component } from ‘react’;

class Counter extends Component {
 constructor(props) {
  super(props);
  this.state = { count: 0 };
 }

 handleClick = () => {
  this.setState({  
 count: this.state.count + 1 });
 };

 render() {
  return  
 (
   <div>
    <p>You clicked {this.state.count} times</p>
    <button onClick={this.handleClick}>Click me</button>
   </div>
  );
 }
}

export default Counter;

This is a class component, created using JavaScript classes that extend the React.Component class.

import React, { useState } from ‘react’;

function Counter() {
const [count, setCount] = useState(0);

const handleClick = () => {
setCount(count + 1);
};

return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}

export default Counter;

This on the other hand is a functional component, written as a simple JavaScript function.

State Management: The Core Difference.

Class components manage their own internal state using this.state. This is typically initialized in the constructor, accessed using this.state object, and updated using the this.setState method, as seen in the code block above.

Functional components were initially stateless. But with the introduction of Hooks, they gained the ability to manage state and lifecycle logic. Utilizing the useState hook for managing state, it returns a pair of values: the current state and a function to update it, as seen above. This is sufficient for simple state management. For more complex state logic involving multiple sub-values, or when the next state depends on the previous one, you want to use useReducer.
For example:

import React, { useReducer } from ‘react’;

const initialState = {
count: 0,
step: 1,
};

const reducer = (state, action) => {
switch (action.type) {
case ‘increment’:
return { …state, count: state.count + state.step };
case ‘decrement’:  

return { …state, count: state.count – state.step };
case ‘setStep’:
return { …state, step: action.payload  
};
default:
throw new Error();
}
};

function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);

const increment = () => dispatch({ type: ‘increment’ });
const decrement = () => dispatch({ type: ‘decrement’  
});
const setStep = (newStep) => dispatch({ type: ‘setStep’, payload: newStep });

return (
<div>
<p>Count: {state.count}</p>
<p>Step: {state.step}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<input type=”number” value={state.step} onChange={(e) => setStep(Number(e.target.value))} />
</div>
);
}

export default Counter;

Here, useReducer is managing multiple state values and complex update logic in a structured and maintainable way. Hooks are exclusively for functional components.

Avoid direct manipulation of the state object in both components.

Never directly modify or mutate the state object, regardless of the component type. Instead, create a new object with the updated values. This approach helps React efficiently track changes and optimize re-renders.

Functional component example:

import React, { useState } from ‘react’;

function UserProfile() {
const [user, setUser] = useState({ name: ‘Jane Doe’, age: 30 });

const handleNameChange = (newName) => {
setUser({ …user, name: newName }); // Create a new object with updated name
};

return (
<div>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<input type=”text” value={user.name} onChange={(e) => handleNameChange(e.target.value)} />
</div>
);
}

export default UserProfile;

Class component example:

import React, { Component } from ‘react’;

class UserProfile extends Component {
state = { user: { name: ‘Jane Doe’, age: 30 } };

handleNameChange = (newName) => {
this.setState(prevState => ({
user: { …prevState.user, name: newName } // Create a new object with updated name
}));
};

render() {
return (
<div>
<p>Name: {this.state.user.name}</p>
<p>Age: {this.state.user.age}</p>
<input type=”text” value={this.state.user.name} onChange={(e) => this.handleNameChange(e.target.value)} />
</div>
);
}
}

export default UserProfile;

In both examples, we’re updating the name property of the user object while preserving the original object’s integrity. This ensures that a new state object is created, preserving immutability and preventing potential issues with state updates. Adherence to this ensures predictable behavior, performance optimizations, and easier debugging.

Class components are for complex logic.

Complex State Management: When dealing with intricate state logic that requires fine-grained control, class components with this.state and this.setState can offer more flexibility.

Lifecycle Methods: For components that heavily rely on lifecycle methods like componentDidMount, componentDidUpdate, or componentWillUnmount, class components are the traditional choice.

Error Boundaries: To handle errors within a component tree and prevent crashes, class components with componentDidCatch are essential.

Performance Optimization: In specific performance-critical scenarios, PureComponent or shouldComponentUpdate within class components can be leveraged.

Legacy Codebases: If you’re working on an existing project that heavily relies on class components, it might be easier to maintain consistency by using them for new components.

Functional components are for simple views.

Simple Components: For presentational components with minimal state or logic, functional components are often the preferred choice due to their simplicity and readability.

State Management with Hooks: Leveraging useState and useReducer in functional components provides a powerful and flexible way to manage state.

Side Effects: The useEffect hook allows for managing side effects like data fetching, subscriptions, or manual DOM (document object model) manipulations.

Performance Optimization: useMemo and useCallback can be used to optimize performance in functional components.

Let your component’s needs guide your decision.

The functional approach is generally considered more concise and readable, and it often suffices due to simplicity and efficiency. However, class components offer more control over state management and lifecycle methods, especially when dealing with intricate logic or performance optimization. This means better structure for organizing complex logic.

The choice between class and functional components is not always clear-cut, as there is no strict rule. Evaluate the requirements of your component and go with the type that aligns best with your project requirements.

Which component do you enjoy working with more?

Please follow and like us:
Pin Share