Answer the question
In order to leave comments, you need to log in
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;
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
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question