Reusable React Hooks

Reusable React Hooks utilities for common tasks

Makerkit uses various React Hooks for very common tasks, such as a simple reducer for asynchronous tasks, or for executing HTTP requests.

useRequestState

You can use this hook as a simple reducer for asynchronous tasks, like HTTP requests or asynchronous operations with Firestore.

To create the hook, you can use the following snippet:

const { state, setError, setData, setLoading } =
useRequestState<Data>();

This hooks returns the current state state and the methods to update it. The state variable has the following interface:

type State<Data, ErrorType> =
| {
data: Data;
loading: false;
success: true;
error: Maybe<ErrorType>;
}
| {
data: undefined;
loading: true;
success: false;
error: Maybe<ErrorType>;
}
| {
data: undefined;
loading: false;
success: false;
error: Maybe<ErrorType>;
};

useApiRequest

You can use this hook to perform HTTP requests from your UI to your API and uses useRequestState under the hood for managing the state.

The function has the following interface:

function useApiRequest<Resp = unknown, Body = void>(
path: string,
method: HttpMethod = 'POST'
)

For example, if we wanted to make an API request to an endpoint, we could do the following:

function SignIn() {
const [signIn, signInState] = useApiRequest(`/api/sign-in`);
useEffect(() => {
if (signInState.success) {
window.location.href = '/dashboard';
}
}, [signInState]);
if (signInState.loading) {
return <span>Loading...</span>
}
return (
<form onSubmit={() => signIn()}></form>
);
}