Next.js Discord

Discord Forum

My code causes bunch of rerenders but don't know what to do

Answered
Rhinelander posted this in #help-forum
Open in Discord
RhinelanderOP
// ...
  const [quantity, setQuantity] = useState(1);
  const [selectedSize, setSelectedSize] = useState(undefined)
  const { addToCart } = useCartContext()

  const handleChange = (e) => {
 // Some logic
    setQuantity(val);
    console.log("Rerendered");
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    const cartItem: CartItem = {
// ...
    };
    addToCart(cartItem);
  };

  return (
    <form
      onSubmit={handleSubmit}
    >
     // The rest of the code
        <Select
          value={selectedSize!}
          onValueChange={setSelectedSize}
        >
          <SelectTrigger>
            <SelectValue placeholder="Izberi velikost" />
          </SelectTrigger>
          <SelectContent>
            <SelectGroup>
              <SelectLabel>Velikosti</SelectLabel>
              {sizes.map((s) => (
                <SelectItem key={s.size} value={s.size}>
                  {s.size}
                </SelectItem>
              ))}
            </SelectGroup>
          </SelectContent>
        </Select>
      </div>
      <div>
        <div>Količina</div>
        <div>
          <Button
            onClick={() => setQuantity((prev) => prev - 1)}
            disabled={quantity <= 0}
          >
            <Minus />
          </Button>
          <input
            type="number"
            value={quantity}
            onChange={handleChange}
          />
          <Button
            onClick={() => setQuantity((prev) => prev + 1)}
            disabled={quantity >= 20}
          >
            <Plus />
          </Button>
        </div>
      </div>

      <Button type="submit">
        <ShoppingBag />
      </Button>
    </form>
  );
}
// ...
Answered by Rhinelander
I know what caused infinite loop - it was cart that refreshed whenever something new was added. But look at this weird behavior
View full answer

9 Replies

RhinelanderOP
I tried to clean up code as much as I could without leaving out the important stuff
Would be really usefull if someone could give me some directions
I know this code is shit but not really sure how to fix it
@Rhinelander typescript // ... const [quantity, setQuantity] = useState(1); const [selectedSize, setSelectedSize] = useState(undefined) const { addToCart } = useCartContext() const handleChange = (e) => { // Some logic setQuantity(val); console.log("Rerendered"); }; const handleSubmit = (event) => { event.preventDefault(); const cartItem: CartItem = { // ... }; addToCart(cartItem); }; return ( <form onSubmit={handleSubmit} > // The rest of the code <Select value={selectedSize!} onValueChange={setSelectedSize} > <SelectTrigger> <SelectValue placeholder="Izberi velikost" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectLabel>Velikosti</SelectLabel> {sizes.map((s) => ( <SelectItem key={s.size} value={s.size}> {s.size} </SelectItem> ))} </SelectGroup> </SelectContent> </Select> </div> <div> <div>Količina</div> <div> <Button onClick={() => setQuantity((prev) => prev - 1)} disabled={quantity <= 0} > <Minus /> </Button> <input type="number" value={quantity} onChange={handleChange} /> <Button onClick={() => setQuantity((prev) => prev + 1)} disabled={quantity >= 20} > <Plus /> </Button> </div> </div> <Button type="submit"> <ShoppingBag /> </Button> </form> ); } // ...
Turkish Van
When it comes to quantity part, I don't see any better solution to that since You are trying to live update it's value as user increase it. (unless You want to convert it into a Server Component and save Your data inside of the URL)

The only thing I see is, in case the Select component, which You use to select the size I guess, is the HTML select tag with its options, attaching the useState hook might be unnecessary.

You might want to attach the useRef hook to it to use its value inside of handleSubmit function, or just pass the formData to it and access its value through it.

That way You wouldn't have the rerender event once user changes the size.
RhinelanderOP
The select is shadcn component and if i am not wrong it uses context by itself. At least i rembember i got error about that when i was implementing it... i wrote like 5 diffrent versions of this component always infinite loop is triggered. I am going to try implement what you said in hopes that it finally works
RhinelanderOP
I know what caused infinite loop - it was cart that refreshed whenever something new was added. But look at this weird behavior
Answer
RhinelanderOP
Give me a minute i am going to send screen recording
RhinelanderOP
RhinelanderOP
Since my problem was fixed I will mark it as solved and create new one for the other problem