A
A
aleks_web_dev2020-05-22 15:16:31
JavaScript
aleks_web_dev, 2020-05-22 15:16:31

Why is the reducer being called twice?

const initialState = {count: 0};

function reducer(state, action) {
//console.log('reducer');  
  switch (action.type) {
    case 'increment':
      //console.log('increment');  
      return {count: state.count + action.num};
    case 'decrement':
      //console.log("decrement");
      return {count: state.count - action.num};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement',num:1})}>-</button>
      <button onClick={() => dispatch({type: 'increment',num:1})}>+</button>
    </>
  );
}

export default Counter;


The essence of the question is this: if you add or decrease a value to the counter, then //console.log('reducer'); called 2 times and //console.log('increment') and //console.log("decrement"); also in this example, the counter works fine if the boolean value changes there, then it works incorrectly
at the first click is called by //console.log('reducer'); 1 time then 2 times.

For example, in this example, I have 1 todo item simply with text and a checkbox, and I have to change its value to the opposite, but due to the fact that the reducer is called 2 times, it does not change
export default function(state, action) {
  switch (action.type) {
    case 'add':
      return [
        ...state,
        {
          id: Date.now(),
          title: action.payload,
          completed: false
        }
      ]
    case 'toggle':
      return state.map(todo => {
        if (todo.id === action.payload) {
          todo.completed = !todo.completed
        }
        return todo
      })
    case 'remove':
      return state.filter(todo => todo.id !== action.payload)
    default:
      return state
  }
}


doesn't work in action.type === 'toggle' value change 2 times

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denioo, 2020-05-22
@Denioo

Dude, your first code is exactly from the documentation (look more closely):
https://ru.reactjs.org/docs/hooks-reference.html#u...
Second, decide on the tags you use the useReducer hook or redux if redux then 2 examples are in the redux documentation.
A more visual explanation of the useReducer hook

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question