Introduction
In React, props are the primary way components receive data from their parents. They allow components to remain flexible and reusable, but what happens when a parent component doesn’t provide a specific prop? Without defaults, your components can behave unpredictably or even break.
Setting default prop values ensures that your components always have meaningful data to work with, improving robustness, maintainability, and developer experience. This is especially important in large applications where components may be reused in multiple contexts, or when integrating with external data sources that may be incomplete or inconsistent.
In this post, we’ll explore how to define default props in React using both functional components and TypeScript, discuss best practices, and show how to combine them with destructuring and modern hooks for clean, readable code. By the end, you’ll have a clear understanding of how to safeguard your components with sensible defaults.
1. Setting Default Props in Functional Components
In modern React (React 16.8+), functional components can define default prop values directly in the function parameter destructuring:
1function Button({ label = 'Click Me', color = 'blue' }) {
2 return <button style={{ backgroundColor: color }}>{label}</button>;
3}
4
5// Usage
6<Button /> // Renders a blue button with "Click Me"
7<Button label="Submit" color="green" /> // Renders a green button with "Submit"
8