File size: 965 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# `useMethods`
React hook that simplifies the `useReducer` implementation.
## Usage
```jsx
import { useMethods } from 'react-use';
const initialState = {
count: 0,
};
function createMethods(state) {
return {
reset() {
return initialState;
},
increment() {
return { ...state, count: state.count + 1 };
},
decrement() {
return { ...state, count: state.count - 1 };
},
};
}
const Demo = () => {
const [state, methods] = useMethods(createMethods, initialState);
return (
<>
<p>Count: {state.count}</p>
<button onClick={methods.decrement}>-</button>
<button onClick={methods.increment}>+</button>
</>
);
};
```
## Reference
```js
const [state, methods] = useMethods(createMethods, initialState);
```
- `createMethods` — function that takes current state and return an object containing methods that return updated state.
- `initialState` — initial value of the state.
|