Using React functional components, it's recommended to no longer use Component.defaultProps
. Default props should be defined in the function params itself, like this:
interface Props { foo?: string, bar?: string,}const Component: FC<Props> = ({ foo = 'hello', bar = 'world' }) => { return ...}
However this only works when props have an optional
?
type, which is then set by the params when a value is undefined. What if I don't want to make my props optional?
For example, this won't work:
interface Props { importantProp: string,}const ImportantComponent: FC<Props> = ({ importantProp = 'not undefined' }) => { return ...}// usageconst SomeOtherComponent = () => { return <ImportantComponent /> // ts-error -> Type '{}' is missing the following properties from type 'Props': importantProp.}
Defining this prop as optional
brings some risks, as it's now also optional when defining its default props. Someone might forget to pass a value to it and now everything will break. (in the worst case):
const ImportantComponent: FC<Props> = ({ importantProp = undefined }) => {}// We can still set `importantProp` to undefined, which should never happen
So, what is a proper solution where default props can be defined without setting them as optional params?