Two different child components using the Zustand store are rendered on every state change. Though the state property they are using in the component is not updated. I am not using the entire store in the components, just try to utilize store slices. Here are the components
//Store
import create from "zustand";
export const useStore = create((set) => ({
shows: [
{
id: Math.floor(Math.random() * 100),
name: "River Where the Moon Rises",
},
{
id: Math.floor(Math.random() * 100),
name: "The Crowned Clown",
},
],
title: 'Default Title',
addShow: (payload) => set((state) => {state.shows.push({id:Math.floor(Math.random() * 100), name:payload})}),
updateTitle: (newTitle) => set({title:newTitle}),
}));
//App - component
function App() {
return (
<>
<ShowManagement />
<TitleManagement />
</>
);
}
export default App;
//ShowManagement - component
import React from 'react'
import { useStore } from "../hooks/useStore";
const ShowManagement = () => {
const { shows } = useStore((state) => ({ shows: state.shows }));
const { addShow } = useStore((state) => ({addShow: state.addShow }));
console.log('ShowManagement - reloaded');
return (
<>
<div>ShowManagement</div>
<ul>
{shows?.map((drama) => {
return (
<li>
{drama.id} - {drama.name}
</li>
);
})}
</ul>
<div>
<input width={200} id="dramaText" />
<button
onClick={() => addShow(document.getElementById("dramaText").value)}
>
Add Drama
</button>
</div>
</>
);
}
export default ShowManagement
//TitleManagement - component
import React from 'react'
import { useStore } from "../hooks/useStore";
const TitleManagement = () => {
const { title } = useStore((state) => ({title:state.title}));
const { updateTitle } = useStore((state) => ({updateTitle: state.updateTitle}));
console.log("TitleManagement - reloaded");
return (
<div>
<p>{title}</p>
<button
onClick={() => updateTitle('Title From UI')}
>
Update Title
</button>
</div>
);
}
export default TitleManagement
The component should not be rendered on other state property changes.
