0

I don't understand the behaviour of my Home Page. When pressing the Button, I would expect that it only logs the new button value in my Console. But it also logs "This is my Test". It appears to me that it execute the entire page again. How can I avoid this behaviour?

enter image description here

import { Button } from "@mui/material";
import type { NextPage } from "next";
import { useValue } from "./visualization/services/customZustand";

const Home: NextPage = () => {
  const value = useValue((state) => state.value);
  const increase = useValue((state) => state.increase);
  console.log("This is my value", value); 
  console.log("This is my Test");  ❓ why is this always executed when pressing the button?

  return (
    <div>
      Hello World, increase value by {value}
      <Button variant="contained" onClick={() => increase(1)}>
        Button
      </Button>
    </div>
  );
};

export default Home;


import { Vector3 } from "@react-three/fiber";
import create from "zustand";

interface ValueState {
  value: number;
  increase: (something: number) => void;
  reset: () => void;
}

export const useValue = create<ValueState>()((set) => ({
  // initial state
  value: 0,

  // method to modify state
  increase: (by: number) => set((state) => ({ value: state.value + by })),
  reset: () => set(() => ({ value: 0 })),
}));


LeSchwambo
  • 674
  • 6
  • 12
  • Take a look at reacts `useEffect` method / and `setState`. – Joel Oct 18 '22 at 10:19
  • This is how react works, it rerenders the whole component whenever state/props changes. Have a look at [the docs](https://reactjs.org/docs/hooks-reference.html#:~:text=The%20setState%20function%20is%20used%20to%20update%20the%20state.%20It%20accepts%20a%20new%20state%20value%20and%20enqueues%20a%20re%2Drender%20of%20the%20component.) – MrBens Oct 18 '22 at 10:20
  • 1
    ah I see sorry for the stupid questions @MrBens – LeSchwambo Oct 18 '22 at 10:41

0 Answers0