Why Would You Build Custom Hooks?
In the previous chapter (Chapter 11, Working with Complex State), when the useReducer()
Hook was introduced, an example was provided in which the Hook was utilized in sending an HTTP request. Here's the relevant, final code again:
const initialHttpState = {
data: null,
isLoading: false,
error: null,
};
function httpReducer(state, action) {
if (action.type === 'FETCH_START') {
return {
...state, // copying the existing state
isLoading: state.data ? false : true,
error: null,
};
}
if (action.type === 'FETCH_ERROR') {
return {
data: null,
isLoading: false,
error: action.payload,
};
}
if (action.type === 'FETCH_SUCCESS') {
return {
data: action.payload,
isLoading: false,
error: null,
};
}
return initialHttpState; // default value for unknown actions
}
function App() {
const [httpState, dispatch] = useReducer(
httpReducer...