Skip to content

Instantly share code, notes, and snippets.

@ovistoica
Created February 14, 2023 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ovistoica/8f9ef3334552816159465b0937def0d6 to your computer and use it in GitHub Desktop.
Save ovistoica/8f9ef3334552816159465b0937def0d6 to your computer and use it in GitHub Desktop.

Good UI Practices

First let's look at the demo of restructuring Users Management to use RTK query and redux toolkit slices and listeners

Redux

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 our Store

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment