immerjs / use-immer

Use immer to drive state with a React hooks
MIT License
4.04k stars 92 forks source link

[useImmerReducer] reducer gets called twice on the initial dispatch - a bug? #11

Closed github0013 closed 5 years ago

github0013 commented 5 years ago
import React from "react"
import { useImmerReducer } from "use-immer"

const initialState = { count: 0 }

function reducer(draft, action) {
  console.log(action.type) // --- here

  switch (action.type) {
    case "reset":
      return initialState
    case "increment":
      return void draft.count++
    case "decrement":
      return void draft.count--
  }
}

function Counter() {
  const [state, dispatch] = useImmerReducer(reducer, initialState)
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </>
  )
}

This is the example code, and I just added console.log line before the switch.
If you click on any of the buttons on this example page, you will see the initial dispatch is run twice.

React_App

But it doesn't run twice again after the initial dispatch, and it logs just once. Is the initial twice call how it's supposed to be?