DEV Community

Discussion on: Optimizing Zustand: How to Prevent Unnecessary Re-renders in Your React App

Collapse
 
benemma profile image
Ben Emma

Amazing, however
however, will produce a type error as

_

keys.reduce is not a function
_

because keys is not an array but rather an object.

The best way around that potential error is to use use a for...in loop to iterate through the keys object like so...

``export const createStoreWithSelectors = (
store: UseBoundStore>
): ((keys: K[]) => Pick) => {
const useStore: (keys: K[]) => Pick = <
K extends keyof T

(
keys: K[]
) => {
return store((state) => {
const x: Partial = {};

  if (Array.isArray(keys)) {
    for (const key of keys) {
      x[key] = state[key];
    }
  }

  return x as Pick<T, K>;
}, shallow);
Enter fullscreen mode Exit fullscreen mode

};

return useStore;
};

Collapse
 
eraywebdev profile image
Eray Kaya

Keys should be provided as an array, as shown in the example. Adding error handling to display a message indicating that keys should be an array would be a nice addition.