reactjs - React Zustand updating store causes other components to re-render - Stack Overflow

admin2025-04-17  3

A simple Zustand store that contain string and set state function:

export const useProductsStore = create<ProductSearchStore>((set) => ({
  searchTerm: "",
  setSearchTerm: (searchTerm) => set({ searchTerm }),
}));

MainLayout component to use with React Router:

export const MainLayout = () => {
  const location = useLocation();
  const { isError, isLoading } = useAuth();

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (isError && !isLoading) {
    return (
      <Navigate
        to={"/login"}
        replace
        state={{
          redirectTo: location,
        }}
      />
    );
  }

  return (
    <div className={"w-full h-screen flex flex-row bg-gray-100"}>
      {/*Sidebar*/}
      <Sidebar />

      {/*Outlet*/}
      <div className={"w-full p-2"}>
        <Outlet />
      </div>
    </div>
  );
};

Inside Sidebar component I'm using useProductStore to read and set value:

  const { searchTerm, setSearchTerm } = useProductsStore();
  .
  .
  .
  <input
    className={"w-full p-1 rounded-md text-xl"}
    placeholder={"Search for product..."}
    value={searchTerm}
    onChange={handleItemSearchTerm}
  />

My issue happens when I update the searchTerm inside component Sidebar it causes the component in <Outlet /> to get a re-render, even though that component and MainLayout does not import useProductsStore. Why?

转载请注明原文地址:http://anycun.com/QandA/1744901712a89230.html