I am building a React app using Redux Toolkit. There are tables with data on the pages that i wanna be able to filter. This is how i handle filtering now.
This is my state.
const initialState = {
loading: false,
clients: [],
filters: {
full_name: '',
platforms: [],
packages: [],
},
total: null,
page: 1,
error: null,
success: false,
};
const clientSlice = createSlice({
name: 'client',
initialState,
reducers: {
setClientFilters: (state, { payload }) => {
state.filters = payload;
state.page = 1; // Reset page to 1 when filters change
},
setClientPage: (state, { payload }) => {
state.page = payload;
}
},
extraReducers: (builder) => {
// Fetching logic here...
}
});
This is my clients page
const { platformFilters, chosenPlatforms, onPlatformFilterChange } = usePlatformFilters();
const { packageFilters, chosenPackages, onPackageFilterChange } = usePackageFilters();
const { debouncedFunction: getClientsSearchDebounce } = useDebounce((searchSrc: string) =>
dispatch(setClientFilters({ ...filters, full_name: searchSrc }))
);
useEffect(() => {
// This triggers unnecessary re-renders
dispatch(setClientFilters({ ...filters, platforms: chosenPlatforms, packages: chosenPackages }));
}, [chosenPlatforms, chosenPackages]);
useEffect(() => {
dispatch(fetchAllClients());
}, [filters, currentPage]);
The issue I am facing is that on the first render, my app re-renders unnecessarily due to the useEffect hook used for updating filters. I am trying to avoid this because the filter state is already available in Redux, and I don’t want to trigger re-renders during the initial load. But i also want to dispatch the action when the dependencies changed. I was trying to use useMemo but it didn’t eliminate the problem. Any help on optimization will be appreciated