Thursday, 29 July 2021

Custom hook built over redux useSelector hook to initialize the global state value in typescript

This hook works same as redux useSelector hook except this can be used to initialize global state for some state object provided the default value of state object is the initializing function. Once the value is initialized, the hook will just return the value, just like using redux useSelector hook.


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);