0
0
ReactHow-ToBeginner · 3 min read

How to Set Default Props in React Components

In React functional components, you set default props by assigning default values in the function parameter using default parameters. This means you write function MyComponent({ propName = defaultValue }) to provide a default if no prop is passed.
📐

Syntax

Use JavaScript default parameters inside the component's parameter list to set default props.

  • { propName = defaultValue }: sets a default value for propName if it is undefined.
  • This works only for functional components.
jsx
function MyComponent({ title = 'Hello' }) {
  return <h1>{title}</h1>;
}
Output
<h1>Hello</h1>
💻

Example

This example shows a functional React component that displays a greeting. If no name prop is passed, it defaults to 'Guest'.

jsx
import React from 'react';

function Greeting({ name = 'Guest' }) {
  return <p>Welcome, {name}!</p>;
}

export default function App() {
  return (
    <>
      <Greeting name="Alice" />
      <Greeting />
    </>
  );
}
Output
<p>Welcome, Alice!</p> <p>Welcome, Guest!</p>
⚠️

Common Pitfalls

Some common mistakes when setting default props in React functional components:

  • Trying to use Component.defaultProps with functional components is discouraged in modern React.
  • Not providing a default value leads to undefined props and possible errors.
  • Setting default props inside the component body instead of parameters can cause bugs.

Always use default parameters in the function signature for clarity and correctness.

jsx
/* Wrong way (legacy): */
function MyComponent({ title }) {
  return <h1>{title}</h1>;
}
MyComponent.defaultProps = { title: 'Hello' };

/* Right way (modern): */
function MyComponent({ title = 'Hello' }) {
  return <h1>{title}</h1>;
}
📊

Quick Reference

  • Use default parameters in function signature: function Comp({ prop = defaultValue })
  • Avoid Component.defaultProps for functional components.
  • Default props help avoid undefined values and improve component stability.

Key Takeaways

Set default props in React functional components using default parameters in the function signature.
Avoid using the legacy Component.defaultProps with functional components.
Default props prevent undefined values and make components more reliable.
Always provide defaults for props that might be missing to avoid runtime errors.
Use destructuring with default values for clear and concise code.