Default props are a React feature that allows developers to assign default values to props. These values are used automatically when a parent component does not pass a specific prop or passes it as undefined. This ensures that the component can still render correctly without breaking.
In React, components often rely on props to display data or control behavior. However, in real-world applications, it is common for some props to be optional. Default props act as a safety net in such cases.
Basic Example of Default Props
Consider a simple Greeting component that displays a message:
function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
If the parent component does not pass the name prop, the output would be “Hello, undefined”. Default props solve this issue.
Using default props with functional components:
function Greeting({ name = "Guest" }) {
return <h1>Hello, {name}</h1>;
}
Now, if no name prop is provided, the component will display “Hello, Guest”.
Default Props Using defaultProps (Older Pattern)
Earlier versions of React commonly used the defaultProps property:
function Button({ label }) {
return <button>{label}</button>;
}
Button.defaultProps = {
label: "Click Me"
};
If the label prop is not passed, the button will still display “Click Me”. While this approach still works, modern React prefers default values using function parameters.
When Default Props Are Applied
Default props are only applied when a prop is undefined. If a prop is passed as null, the default value will not be used. This distinction is important when handling optional data.
Example:
<Greeting name={null} />
This will render “Hello, null” instead of using the default value.
Real-World Example
In a real-world application like a reusable Button or Card component, default props are commonly used for styling, labels, or behavior flags.
Example:
function Button({ label = "Submit", type = "button" }) {
return <button type={type}>{label}</button>;
}
This allows developers to reuse the Button component without repeatedly passing the same props, while still allowing customization when needed.
Best Practices and Important Notes
Default props should be used for optional values, not for required data. If a prop is mandatory for a component to function correctly, it should be clearly documented and validated rather than defaulted silently.
Avoid overusing default props to hide logical issues. Defaults should provide sensible fallbacks, not mask missing or incorrect data.
In summary, default props improve component reliability by providing fallback values for missing props. They make components easier to reuse, safer to use, and more predictable in real-world React applications.