Example 1
import React, { useReducer } from 'react';
const initialState = {
count: 2
}
const reducer = (state, action) => {
switch(action){
case 'INCREMENT':
return {count: state.count + 1}
case 'DECREMENT':
return {count: state.count - 1}
case 'DOUBLE_INCRE':
return {count: state.count * 2}
case 'RESET':
return {count: 0}
default:
return state
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<div className="">
<h1>Counter</h1>
<h2>Count: { state.count } </h2>
<button onClick={() => dispatch('INCREMENT')}>+</button>
<button onClick={() => dispatch('DECREMENT')}>-</button>
<button onClick={() => dispatch('DOUBLE_INCRE')}>++</button>
<button onClick={() => dispatch('RESET')}>0</button>
</div>
);
}
export default Counter;
Example 2
import React, { useState, useReducer, useEffect } from 'react';
// NameList is like this
// const initialState = [
// {name: 'John'}
// ]
const reducer = (state, action) => {
switch(action){
case 'INCREMENT':
return [...state, {name: 'John'}]
case 'RESET':
return []
default:
return state
}
}
function ReactList(props) {
const [stateList, dispatch] = useReducer(reducer, props.NameList)
return (
<div className="lists">
<h1>List</h1>
<button onClick={() => dispatch('INCREMENT')}>+</button>
<button onClick={() => dispatch('RESET')}>-</button>
<h4>Sum Age{ sumage }</h4>
{
stateList.map((item, idx) => {
return <div key={item.name}>
<h3>{ item.name }</h3>
</div>
})
}
</div>
);
}
export default ReactList;