import React, {
useReducer
}
from
'react'
;
const initialState = {
count: 0,
isEven:
false
};
const actionTypes = {
INCREMENT:
'INCREMENT'
,
DECREMENT:
'DECREMENT'
,
RESET:
'RESET'
};
const reducer = (state, action) => {
switch
(action.type) {
case
actionTypes.INCREMENT:
return
{
...state,
count: state.count + 1,
isEven: (state.count + 1) % 2 === 0
};
case
actionTypes.DECREMENT:
return
{
...state,
count: state.count - 1,
isEven: (state.count - 1) % 2 === 0
};
case
actionTypes.RESET:
return
initialState;
default
:
return
state;
}
};
const ComplexStateComponent = () => {
const [state, dispatch] = useReducer(reducer,
initialState);
return
(
<div>
<p>Count: {state.count}</p>
<p>Is Even: {state.isEven ?
'Yes'
:
'No'
}</p>
<button onClick={() =>
dispatch({ type: actionTypes.INCREMENT })}>
Increment
</button>
<button onClick={() =>
dispatch({ type: actionTypes.DECREMENT })}>
Decrement
</button>
<button onClick={() =>
dispatch({ type: actionTypes.RESET })}>
Reset
</button>
</div>
);
};
export
default
ComplexStateComponent;