I am using this custom http hook inside different components.
function useHttp(requestFunction, startWithPending = false) {
const httpState = useSelector((state) => state.http);
const dispatch = useDispatch();
const sendRequest = useCallback(
async function (requestData) {
dispatch(httpActions.loading(startWithPending));
try {
const responseData = await requestFunction(requestData);
dispatch(httpActions.success(responseData));
} catch (error) {
dispatch(httpActions.error(error.message || "Something went wrong!!!"));
}
},
[dispatch, requestFunction, startWithPending]
);
return {
sendRequest,
...httpState,
};
}
And I am managing states using Redux toolkit (my http actions).
const initialHttpState = {
status: null,
data: null,
error: null,
};
const httpSlice = createSlice({
name: 'http',
initialState: initialHttpState,
reducers: {
loading(state, action){
state.status = action.payload ? 'pending' : 'null';
state.data = null;
state.error = null;
},
success(state, action){
state.status = 'completed';
state.data = action.payload;
state.error = 'null'
},
error(state, action){
state.status = 'error';
state.data = null;
state.error = action.payload;
}
}
})
And I am using this hook inside useEffect's of multiple components:
const { sendRequest, data, status, error } = useHttp(getProducts, true);
useEffect(() => {
sendRequest();
}, [sendRequest]);
My problem is since different components use the same hook, whenever I tried to call this custom hook inside a component, any other component who uses this same hook get's re-rendered and it causes my app to crash (can't read properties of undefined error) because as you see I'm overwriting response data to the same place and also status are changing.
How can I avoid this re-render problem? Inside my component how can I check whether this re-render demand comes from other components or the component itself? Or how can I change my state management structure to handle this problem?