Skip to content

Conversation

@kangaroooh
Copy link

Use default reducer state value as initial state when using useReducer hook

Based on discussion from issue facebook#14542.

If we provide the following reducer:

function reducer(state = 5, { type }) {
  switch (type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
}

Then in the component:

function Counter() {
  const [count] = useReducer(reducer);
  return <span>{count}</span>;
}

We don't get count equal 5 in the initial render.

It works if we provide the initialState as second argument for useReducer:

const [count] = useReducer(reducer, 5);

or like @ckknight mentioned if we call an initialization action:

useReducer(reducer, undefined, { type: 'INIT' });

However I think it's a little redundant because we already set the default state value in the reducer function.

This pull request add some changes to use the default state value from the reducer function if no initialState was provided to useReducer.

I don't know if this behaviour was discussed during the implementation of useReducer, but if this is not the desired behaviour for useReducer feel free to close this pull request.

@softagram-bot
Copy link

Softagram Impact Report for pull/12 (head commit: 4e6c790)

⭐ Visual Overview

Changed elements and changed dependencies.
Changed dependencies - click for full size
Graph legend
(Open in Softagram Desktop for full details)

⭐ Change Impact

How the changed files are used by the rest of the project
Impacted files - click for full size
Graph legend
(Open in Softagram Desktop for full details)

💡 Insights

  • Co-change Alert: You modified ReactFiberHooks.js. Often ReactHooks-test.internal.js (src/tests) is modified at the same time.

📄 Full report

Give feedback of this report to [email protected]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants