How to be Better in React Code Reusability - Part 1
March 16, 2023
A Brief Overview of React and Its Popularity
React is one of the most popular front-end JavaScript libraries for building user interfaces. Developed by Facebook, React has gained a vast following in the web development community due to its simplicity, flexibility, and scalability.
React's popularity can be attributed to its component-based architecture, which allows developers to break down complex user interfaces into small, reusable parts. These smaller components can then be composed to create larger, more complex UIs quickly.
However, as applications grow, managing the codebase becomes challenging. This is where code reusability comes in — writing reusable code that can be shared across different parts of an application (and even across multiple projects). It saves time, reduces errors, and improves scalability and maintainability.
In this article, we’ll explore how to implement code reusability in React, its importance, and best practices.
React Components and Their Importance in Reusability
Components are the building blocks of React. When designed for reusability, they can be imported and integrated across different parts of an app, speeding up development and reducing duplication.
Comparison: Functional vs. Class Components
Functional Components
- Simpler, concise, easier to test and maintain.
- Take
propsas input and return JSX. - Commonly used with hooks for state and lifecycle logic.
- Ideal for stateless UI pieces or logic that can be wrapped in custom hooks.
Example:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
This Welcome component can be reused anywhere in the app with different name props.
Class Components
- More powerful, with state and lifecycle methods.
- Verbose and harder to maintain but useful in certain scenarios.
Example:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: props.seconds };
}
tick() {
this.setState((state) => ({
seconds: state.seconds - 1,
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div>Seconds remaining: {this.state.seconds}</div>;
}
}
The timer is reusable by simply passing different seconds props.
Examples of Reusable Components in React
1. Button Component
function Button(props) {
return <button onClick={props.onClick}>{props.label}</button>;
}
2. Modal Component
function Modal(props) {
return (
<div className="modal">
<div className="modal-content">{props.children}</div>
</div>
);
}
3. Form Input Component
function FormInput(props) {
return (
<div>
<label>{props.label}</label>
<input type={props.type} value={props.value} onChange={props.onChange} />
</div>
);
}
Best Practices for Code Reusability
1. Use Props and State
- Use
propsfor customization. - Use
statefor managing dynamic behavior. - Combine both for flexible, reusable components.
2. Higher-Order Components (HOCs)
HOCs wrap components with additional functionality.
Example – Authentication:
function withAuth(WrappedComponent) {
return class extends React.Component {
state = { isAuthenticated: false };
componentDidMount() {
const isAuthenticated = true; // Replace with real check
this.setState({ isAuthenticated });
}
render() {
return this.state.isAuthenticated ? <WrappedComponent {...this.props} /> : null;
}
};
}
3. Render Props
Render props let you share logic between components by passing a function.
Example:
class Mouse extends React.Component {
state = { x: 0, y: 0 };
handleMouseMove = (event) => {
this.setState({ x: event.clientX, y: event.clientY });
};
render() {
return <div onMouseMove={this.handleMouseMove}>{this.props.render(this.state)}</div>;
}
}
Usage:
<Mouse render={({ x, y }) => <p>Mouse position: {x}, {y}</p>} />
Conclusion
Code reusability is a key factor in scalable React development. By leveraging:
- Functional and class components
- Higher-order components
- Render props
…developers can build flexible, maintainable, and modular applications.
Reusable components improve productivity, consistency, and long-term maintainability, making them a best practice for all serious React projects.