Is it possible to specify non-primitive defaults for props
in React, that are not shared across all instances?
Since the result of getDefaultProps()
is cached and reused for all instances, it is not a safe place to specify non-primitive defaults.
However, components are not supposed to modify their own props
, so e.g. setting non-primitive values on props
in the constructor is a no-no. (In fact, props
is immutable; React
ensures this via Object.preventExtensions
.)
Not sure how else to make this happen...
props
are immutable. getDefaultProps
is for supplying prop values to components when they aren't specified when created. props
can be any valid javascript value, including nested objects, as long as they don't change.
Because props
are immutable, default props are cached and shared between all instances of an object.
For things that change during the lifetime of a component, you want to use state
. To specify the initial shape of your component's state, you want to use the getInitialState()
function. this.props
will be available in that function.