1.1.6 • Published 5 years ago
@jsxtools/react-hooks v1.1.6
react-hooks
react-hooks is a tree-shakable collection of hooks for React.
It is 541 bytes (262 gzipped).
useDebouncedState
useDebouncedState provides a state and setter that throttle updates coming in rapid succession.
import { useDebouncedState } from '@jsxtools/react-hooks';
function Component() {
// successive updates to `searchTerm` to will be deferred by 400 milliseconds
const [searchTerm, setSearchTerm] = useDebouncedState(initialState, 400);
const onSearchTermInput = event => setSearchTerm(event.target.value);
return (
<p>
<label htmlFor="q">Search</label>
<input id="q" name="q" defaultValue="" onInput={onSearchTermInput}>
</p>
)
}
useEqualState
useEqualState provides a state and setter that check for shallow or deep changes.
import { useEqualState } from '@jsxtools/react-hooks';
function Component() {
// shallow updates to `formData` will not trigger re-renders
const [formData, setFormData] = useEqualState({ givenName: 'Jonathan', familyName: 'Neal' });
const onGivenNameInput = event => setFormData({ ...formData, givenName: event.target.value });
const onFamilyNameInput = event => setFormData({ ...formData, familyName: event.target.value });
return (
<>
<p>
<label htmlFor="gn">Given Name</label>
<input id="gn" defaultValue={formData.givenName} onInput={onGivenNameInput} />
</p>
<p>
<label htmlFor="fn">Family Name</label>
<input id="fn" defaultValue={formData.familyName} onInput={onFamilyNameInput} />
</p>
</>
);
}
useLocalStorage
useLocalStorage provides a state and setter bound to Local Storage.
import { useLocalStorage } from '@jsxtools/react-hooks';
function Component() {
// the `value` of `counter` will persist after the browser is refreshed
const [value, setValue] = useLocalStorage('counter', 0);
const inc = setValue.bind(null, value + 1);
const dec = setValue.bind(null, value - 1);
return (
<p>
<span>Value is "{value}".</span>
<button aria-label="decrement value" onClick={dec}>-</button>
<button aria-label="increment value" onClick={inc}>+</button>
</p>
);
}
usePromise
usePromise provides a state and settled value of a Promise.
import { usePromise } from '@jsxtools/react-hooks';
function Component () {
// the `state` is "pending", "fulfilled", or "rejected"
// the `settledValue` is the fulfilled or rejected value
const [ state, settledValue ] = usePromise(async () => {
const response = await fetch(URL);
const json = await response.json();
return json;
});
return state === 'pending'
? 'Loading'
: JSON.stringify(settledValue);
}
Installation
npm install @jsxtools/react-hooks
Usage
import reactHooks from '@jsxtools/react-hooks';
reactHooks();