why does react js renders two times when setting a state

Abdullah Manafikhi

I have this code that uses useState to make a form appear or disapear when clicking a button

    const [searchClick, setSearchClick] = useState("hidden")

         // Button when clicked the form appears or disappears
        <label onClick={() => setSearchClick(prevState => prevState ==='hidden' ? 'flex' : 'hidden') } className="btn-xs btn-ghost rounded-full w-fit h-fit swap swap-rotate" >
            <input  type="checkbox" />
            <Search className="swap-off relative right-1" width="22px" height="22px" fill='#8DD0BA' />
            <svg className="swap-on fill-current" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 512 512"><polygon points="400 145.49 366.51 112 256 222.51 145.49 112 112 145.49 222.51 256 112 366.51 145.49 400 256 289.49 366.51 400 400 366.51 289.49 256 400 145.49"/></svg>
        </label>

        <form className={`${searchClick} my-6 justify-center`}>
            <input type="text" placeholder="Search" className="input input-bordered max-w-lg bg-white text-black" />
            <button className="btn w-18 rounded-r-none"><Search /></button>
        </form>

when I'm putting the onclick function in the label tag it causing two renders and it's not working well but when I'm putting it in the input tag it's working well

Libor

The problem is not in React rendering, but in handling label clicks. Your handling function is first triggered from label or its children svg or polygon (causing render) and then from input (another render). It can be logged and debugged like this with event.target:

function YourComponent() {
  const [searchClick, setSearchClick] = useState("hidden");

  const onClickFnc = (event) => {
    console.log("onClick called", event.target);
    setSearchClick((prevState) => (prevState === "hidden" ? "flex" : "hidden"));
  };

  console.log("rendering component");

  return (
    <div>
      <label
        onClick={onClickFnc}
        className="btn-xs btn-ghost rounded-full w-fit h-fit swap swap-rotate"
      >
        <input type="checkbox" />
        <svg
          className="swap-on fill-current"
          xmlns="http://www.w3.org/2000/svg"
          width="32"
          height="32"
          viewBox="0 0 512 512"
        >
          <polygon points="400 145.49 366.51 112 256 222.51 145.49 112 112 145.49 222.51 256 112 366.51 145.49 400 256 289.49 366.51 400 400 366.51 289.49 256 400 145.49" />
        </svg>
      </label>
      <div>Current state: {searchClick}</div>
    </div>
  );
}

It can be solved by adding handler on input and some event.stopPropagation(), nice example here: https://stackoverflow.com/a/38958110/5940854

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Can't figure out why React state is changing when I am not mutating any of the data or setting state anywhere

React - setting state with data does not work/ sets its to an empty array - why?

Why does call glBindBuffer() two times?

When does state update in React

The react component renders several times when using useEffect

React: setting a state Hook causes error - Too many re-renders. React limits the number of renders to prevent an infinite loop

Will a react component reset its state when it re-renders?

Too many re-renders. When setting state

React renders without actually changing the state when setInterval is used

Why does setting state in child component onclick cause recursive loop even when button not clicked?

React state is undefined when setting it with a hook

Why the object disappeared when listed for two times?

Why does state not update correctly when calling setState() multiple times

Where to put conditional statement when setting state in React.js?

React - Why does state object get updated when I update a restructured copy of state?

Setting two state variable onClick in React

Why does React render component for the second time after setting the state to the same value?

Why does React state not change when called a second time?

Too many re-renders on setting state

Sorting data (in a state) when state gets updated (React) - renders with delay

Why my value of array is changing when I'm setting state of other object in react?

React useState. Why do the docs advise passing a function with the previous state when setting the state?

Why my React component does not rerender when Set state was changed?

React losing state when component re-renders

Why does the POST stop working when setting state in useEffect?

React renders previous state on state change

Why when setting the state in React doesn't give the right value all the time?

Why does React render the page two times?

why does React counter component print two times console.log?