Search code examples
javascriptreactjsreact-props

What is the best way to set default value of Props?


There are a few props in my application which are received from the reducer-selector.

I was wondering, should I set default values for the props at all the below mentioned places ?

  1. at defaultProps
  2. in reducer
  3. in selector

Or should I define the default value at only 1 of these 3 places, and why ?


Solution

  • It is advisable to set default values in only one place. Because if it is set in one place you don't have to bother again and again in different components, selectors, etc. This will also avoid bugs due to default values.

    1. at defaultProps: If you set defaultProps you will end up setting default value in multiple components if prop is used in multiple components. If you miss, inconsistency in results shown on UI.
    2. in selector: If you are using the same prop from a store in multiple selectors, you have to set the default value before returning the result. Again not a good approach.
    3. in reducer: This is the place from where the prop will be set in store. Once you set default value, it will be used across all components, selectors without any change.

    I think, Setting in reduce looks more promising and stable approach considering an extensible App.