First let's look at the demo of restructuring Users Management to use RTK query and redux toolkit slices and listeners
Do's
-
Use RTK Query for most common API requests Ex: ``
-
Normalize the output using
createEntityAdapter
-
Use redux slice for reducers and actions
-
Use
listeners
for more complicated state modifications Ex:
export const addAdminUserDetailsToListListener =
startAppListening({
// Whenever an action from RTK Query happens
matcher: userManagementApi.endpoints.getAdminUser.matchFulfilled,
// Do this effect
effect: ({ payload }, listenerApi) => {
listenerApi.dispatch(
userManagementApi.util.updateQueryData(
'getAdminUsers',
undefined,
(draft) => {
adminUsersAdapter.upsertOne(draft, {
...payload,
fetched: true,
} as unknown as EntityUser);
},
),
);
listenerApi.dispatch(clearUpdatingUser());
},
});
- Use the selectors
useAppDispatch
&useAppSelector
that are typed with ourStore
Do not
- Most state logic should be kept in Redux
- Don't duplicate redux state in a separate
Config Class
- Don't duplicate redux state in local state: Can lead to re-rerenders and multiple dispatches