Functional vs. Class Components in React
Understand the past and master the present of React by comparing the two fundamental ways to build components.
/* Component evolution... */
Functional Components: The Modern Standard
Functional components are modern JavaScript functions that accept props and return JSX. They are concise, easy to read, and with the introduction of Hooks, they can now manage state and side effects, making them the standard for new React development.
Class Components: The Original Blueprint
Class components are ES6 classes that extend `React.Component`. They use a `render()` method to return JSX and manage state through `this.state` and `this.setState()`. While still functional, they are considered legacy and are more verbose than their functional counterparts.
State Management: useState vs. this.state
In functional components, we use the `useState` Hook to manage state. In class components, state is an object initialized in the `constructor` and updated with `this.setState()`. Hooks provide a more direct and less boilerplate way to handle component state.
Side Effects: useEffect vs. Lifecycle Methods
Class components use lifecycle methods like `componentDidMount` and `componentWillUnmount` to run code at specific times. Functional components achieve the same with the versatile `useEffect` Hook, which can handle component mounting, updating, and unmounting all in one place.
Practice Zone
Interactive Test 1: Match the Concept
Match the React concept to its corresponding component type.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Complete the Class
Rellena los huecos en cada casilla.
class Counter React.Component { (props) { super(props); this. = { count: 0 }; } () { return <h1>Count: {this.state.count}</h1>; } }
Practice Example: Refactor to Functional
Convert the following Class Component into a Functional Component using the `useState` Hook.
Practical Implications
Understanding the shift from class to functional components is key to writing modern, efficient, and maintainable React code.
1. Reusing Logic: Custom Hooks vs. HOCs
With class components, developers used patterns like Higher-Order Components (HOCs) and Render Props to share logic. Functional components introduced Custom Hooks (e.g., `useAuth`, `useFetch`), a much simpler and more powerful way to extract and reuse stateful logic without extra component nesting.
// Custom Hook: clean, reusable logic
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
// ... logic to update width
return width;
}
function MyComponent() {
const width = useWindowWidth(); // Simple to use
return <div>Window width is {width}</div>;
}
2. Readability and Conciseness
Functional components are less verbose. There's no need for `this`, `constructor`, or binding methods. Logic related to a specific feature can be grouped together inside a single `useEffect` hook, rather than being split across `componentDidMount` and `componentDidUpdate`.
Class
class Example extends C {
constructor(props) {
super(props);
this.state = { a: 1 };
this.handleClick =
this.handleClick.bind(this);
}
handleClick() { ... }
render() { ... }
}
Functional
function Example() {
const [a, setA] =
useState(1);
function handleClick() { ... }
return ...
}
3. Working with Legacy Code
While all new code should be written with functional components, you will inevitably encounter class components in older codebases. Understanding both is crucial for a professional React developer. Thankfully, you can mix both types of components in the same application seamlessly.
Practical Takeaway: Embrace functional components and Hooks for their simplicity and power. While knowledge of class components is necessary for maintenance, your future is functional.
Component Glossary
- Functional Component
- A standard JavaScript function that accepts an object of properties ("props") and returns a React element that describes the UI.
- Class Component
- An ES6 class that extends `React.Component`. It must include a `render()` method and can manage its own state and lifecycle.
- Hooks
- Special functions (e.g., `useState`, `useEffect`) that let you "hook into" React features like state and lifecycle from within functional components.
- State
- An object that represents the parts of the app that can change. Each component can maintain its own state. A change in state triggers a re-render.
- Lifecycle
- The series of phases a component goes through from its creation (mounting) to its destruction (unmounting). Methods like `componentDidMount` or the `useEffect` Hook allow you to run code at these specific points.