I'm trying to create some hooks to fetch slices of the Redux store so that the store can't access directly to return anything.
If I useSelector directly in the component it works great and doesn't unnecessarily re-render:
*** Modal.tsx ***
const { isModalOpen } = useSelector((state: RootState) => state.carsSlice); // Works great. No unnecessary re-renders
If I create a hook to return the carsSlice then it unnecessarily re-renders the whole page. Why?
E.g.,
*** StateHooks.ts ***
const useGlobalState = () => useSelector((state: RootState) => state);
export const useCarsState = () => useGlobalState().carsSlice;
*** Modal.tsx ***
const { isModalOpen } = useCarsState(); // Re-renders underlying page and is significantly slower than above approach
I'm fetching the specific value from the state so I don't understand why it would re-render the whole page it is being used on? Is there a way to do this?
I've also tried the below but it still causes page re-render:
const useCarsState = useSelector((state: RootState) => state.carsSlice); // Same result
The only way it works as expected is the below BUT I want the custom hooks above:
const { isModalOpen } = useSelector((state: RootState) => state.carsSlice); // Works great
Thanks all.