Code
The custom hook: useLazySelector.ts
import {useEffect} from 'react';
import {DefaultRootState, useSelector} from 'react-redux';export function useLazySelector<TState = DefaultRootState,
TSelected = unknown>(
selector: (state: TState) => TSelected,
equalityFn?: (left: TSelected, right: TSelected) => boolean) {
const value = useSelector(selector, equalityFn);
useEffect(() => {
if (typeof value === 'function') {
value();
}
}, [value]);
if (typeof value === 'function') {
return null;
}
return value;
}
Example on how to use it.
Note: I am using redux-rematch (Git Reference) to get rid of boilerplate code of redux.
The model: student.ts
import {ModelConfig} from '@rematch/core';;
import {dispatch} from 'store';
export interface State {
students: Array<Object>,
}
export const students: ModelConfig<State> = {
state: {
students: (() => dispatch.students.loadStudents()) as any,
},
reducers: {
setStudents: (state, payload) =>
Object.assign({}, state, {student: payload}),
},
effects: () => ({
async loadStudents() {
// code to call api, load data and then set state for
dispatch.students.setStudents(response.data);
},
}),
};
The component: student.tsx
const students =
useLazySelector((state: {students: State}) =>
state.students.students);