useReducer
元のuseReducerのコード
import React, { useState, useReducer } from 'react';
import ReactDOM from 'react-dom';
const App = () => {
const [state, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case 'ADD': {
return { ...state, count: state.count + 1 };
}
case 'SUBTRACT': {
return { ...state, count: state.count - 1 };
}
default: {
return state;
}
}
},
{
count: 0,
}
);
let { count } = state;
const add = () => {
dispatch({ type: 'ADD' });
};
const subtract = () => {
if (count > 0) {
dispatch({ type: 'SUBTRACT' });
}
};
return (
<div>
<button onClick={subtract}>-</button>
<div>{count}</div>
<button onClick={add}>+</button>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
userReducerをラップしたカスタムフックのコード
import React, { useReducer } from 'react';
import ReactDOM from 'react-dom';
function useCounter() {
const [state, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case 'ADD': {
return { ...state, count: state.count + 1 };
}
case 'SUBTRACT': {
return { ...state, count: state.count - 1 };
}
default: {
return state;
}
}
},
{
count: 0,
}
);
return [state, dispatch];
}
const App = () => {
const [state, dispatch] = useCounter();
let { count } = state;
const add = () => {
dispatch({ type: 'ADD' });
};
const subtract = () => {
if (count > 0) {
dispatch({ type: 'SUBTRACT' });
}
};
return (
<div>
<button onClick={subtract}>-</button>
<div>{count}</div>
<button onClick={add}>+</button>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));