When you don’t want to specify each props value of a component, you can use optional props with default values. The component will use the default value when you don’t pass a value to the prop.
Set a React optional props with default value
- Mark the props variable optional using a question mark
?
- Provide default values when destructuring from a type definition
function UserPage({ name, age, gender=1 }: { name: string, age: number, gender?:number }) { return <> <p>name: {name}</p> <p>age: {age}</p> <p>gender: {gender?'Male':'Female'}</p> </>; }
or you can split the type definition into separate
interface
. This is the above code, but with type definition separated into an interface
.interface UserPageProps = { name: string, age: number, gender?: number }; function UserPage({ name, age, gender = 1 }: UserPageProps) { return ( <> <p>name: {name}</p> <p>age: {age}</p> <p>gender: {gender ? 'Male' : 'Female'}</p> </> ); }
Next, this is how to use the
UserPage
component in your React application:export default function App() { return ( <div> <UserPage name="John Doe" age={30} /> <UserPage name="Jane Doe" age={25} gender={2} /> </div> ); }
You can pass a gender value when you don’t want to use the default
1
so the page will show a Female
gender.When to use optional props
Client doesn’t need to pass props explicitly
You use optional props when the component doesn’t need client code to specify props value as it is not required. The component already provides a default value so that default was applied to the component. If the client wants a different behavior, then they can pass props value.
Update a legacy code
When you want to update existing component props that already scattered across codebase, you may need to introduce the new props as optional so it wont break client code.
Don’t overuse optional props
However, it is important to note that while optional props is super useful to ease component usage, overusing them can cause harm to the overall codebase. The client cannot know what makes a component behave strangely or not meet their expectations because of the default value of some props.
Hence, use optional props sparingly and only when necessary. Or you can design a composable component that can free the client to using optional props.
Conclusion
In conclusion, optional props with default values are a useful feature in React and TypeScript that allow you to set default values for props in a component. This feature can help you avoid errors that may occur when a prop is not passed to a component. You can make a prop optional by adding the question mark symbol after the prop name, and you can provide default values when destructuring from a type definition. However, it is important to use optional props sparingly and only when necessary, as overusing them can cause harm to the overall codebase.