why function in react app will not render

Advertisements

The code runs without errors on the console.Even after i write the if block no error is in the console,but the react app wont display any JSX ,just blank page

my code works when you remove the if(} block

import { useState } from "react";
const Zoom = () => {
  const [btnable, setbtnable] = useState(true);
  const [stoke, setStoke] = useState("");
    if (stoke === "") {
      setbtnable(btnable);
    } else {
      setbtnable(false);
    }

  return (
    <div className="container">
      <span>Zoom</span>
      <table>
        <tr>
          <td>1</td>
          <td>2</td>
          <td>3</td>
        </tr>
        <tr>
          <td>4</td>
          <td>5</td>
          <td>6</td>
        </tr>
        <tr>
          <td>7</td>
          <td>8</td>
          <td>9</td>
        </tr>
        <tr>
          <td>10</td>
          <td>11</td>
          <td>12</td>
        </tr>
      </table>
      <br />
      <input
        type="number"
        placeholder="Stoke"
        onChange={(e) => {
          setStoke(e.target.value);
        }}
      />
      <button disabled={btnable}>Zoom</button>
    </div>
  );
};

export default Zoom;

>Solution :

The issue is an infinite render.

When you update component state, you cause that component to rerender.

Every time the component rerenders, the if else block is being run again. Which is calling set state again. Which is causing the component to rerender, and calling the if else again, and setting state again, rendering again and…. you get the point. It’s an infinite loop.

When you’re doing this upfront logic that causes state to change, you should wrap it in a useEffect – that way you won’t get stuck in an infinite loop of rerendering on state changes.

Your code is confusing me and you didn’t explain what you want the behavior to be. But my guess is you want this, or at least something like it:

const [btnable, setBtnable] = useState(true);
const [stoke, setStoke] = useState("");

useEffect(() => {
   if (stoke === "") {
      setBtnable(true);
   } else {
      setBtnable(false);
   }
}, [stoke]);

Read up on component rendering, state changes, useState and useEffect hooks. Seems like you’re missing some key insights which is causing your confusion here. Best of luck.

Leave a ReplyCancel reply