I was reading the Redux documentation and something really confused me. Many, if not all, of the example reducer functions in the documentation have this kind of signature:
function visibilityFilter(state = 'SHOW_ALL', action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter
default:
return state
}
}
What is the point of providing a default state
when the action
is required anyway?
In that particular code sample, calling visibilityFilter
without providing an action
argument will result in a TypeError
at the switch statement.
But in order to provide an action
parameter, the state
parameter must also be provided, and so the default value is overridden and useless. As far as I know, there is simply no way in the JavaScript syntax to call that visiblityFilter
function while providing only the action
parameter.
Is that just some funky/bad coding style in the world of Redux? What am I missing?
That's some pretty strange code, but there is one case where the default parameter could be used - if undefined
is explicitly passed as the first parameter:
function visibilityFilter(state = 'SHOW_ALL', action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter
default:
return state
}
}
console.log(visibilityFilter(undefined, {}));
(not that I would recommend writing code that looks like this in most cases)
With Redux in particular, this sort of thing can arise "naturally" because the function is a reducer, used with createStore
. If createStore
is passed an initial state, it'll be passed along to the reducer as the reducer's first argument; otherwise, Redux's internals will explicitly call it with an undefined
first argument.