https://github.com/jacob-ebey/react-hook-utils
Utilities for working with react-hooks.
https://github.com/jacob-ebey/react-hook-utils
Last synced: 4 months ago
JSON representation
Utilities for working with react-hooks.
- Host: GitHub
- URL: https://github.com/jacob-ebey/react-hook-utils
- Owner: jacob-ebey
- Created: 2018-11-13T23:42:44.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-11-15T06:47:17.000Z (over 7 years ago)
- Last Synced: 2025-10-17T10:45:06.155Z (8 months ago)
- Language: JavaScript
- Size: 445 KB
- Stars: 9
- Watchers: 1
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# react-hook-utils
>
[](https://circleci.com/gh/jacob-ebey/react-hook-utils) [](https://coveralls.io/github/jacob-ebey/react-hook-utils?branch=master) [](https://www.npmjs.com/package/react-hook-utils)
## Install
```bash
npm install --save react-hook-utils
```
## Documentation
https://jacob-ebey.github.io/react-hook-utils/
## Usage
### Global Reducer
Create a global reducer for re-use in components:
```jsx
// useCount.js
import { globalReducer } from "react-hook-utils";
export default globalReducer(
{ count: 0 },
{
decrement: state => ({
...state,
count: state.count - 1
}),
increment: state => ({
...state,
count: state.count + 1
})
set: (state, count) => ({
...state,
count
}),
}
);
```
Use the reducer within a component:
```jsx
import React, { useCallback } from "react";
import useCount from "./useCount";
export function CountControls() {
// Select only the count property from the state
const [count, { decrement, increment, set }] = useCount(s => s.count);
// Create a callback to reset the count
const reset = useCallback(() => set(0), [set]);
return (
-
{count}
+
Reset
);
}
```
### Use Promise
In the following example, API.getUserAsync returns a Promise. We combine usePromise with useMemo as follows to only make an API call when the userId changes:
```jsx
import React, { useMemo } from "react";
import { usePromise } from "react-hook-utils";
import API from "./api";
export function UserView({ userId }) {
const [user, error, loading] = usePromise(
useMemo(() => API.getUserAsync(userId), [userId])
);
if (loading) {
return
Loading...;
} else if (error) {
return Something went wrong :(;
}
return
Hello, {user.name};
}
```
## License
MIT © [](https://github.com/)