skip to Main Content

I am new to react , for learning i created a simple incrementor , i used object as input instead of simple string or number , whenever i clicked increment , it render the component due to change in value and then i click reset button it set count to 0.

But for curiosity , i clicked multiple times a reset render , it render every time even there is no change in dom. As of i know it render because the object was created newly every time.
How to stop the render when i click reset button multiple times?

import { Fragment, useReducer, useRef, useState,useMemo, useEffect } from "react"

export default function Sample()
{ 
   const [num,setnum]=useState({count:0})
   const inc =()=>{
   setnum((prevstate)=>({...num,count:prevstate.count+1}))
   }
   const reset =()=>{
    console.log("render")
    setnum({...num,count:0})
   }
   return(
    <div>
       <button>{num.count}</button>
       <button onClick={inc}>Increment</button>
       <button onClick={reset}>reset</button>
    </div>
   )
}

2

Answers


  1. Rewrite the reset like below :

    const reset =()=> {
        console.log("render")
        if(num.count){ setnum({...num,count:0})}      
    }
    
    Login or Signup to reply.
  2. Calling the setter from the useState Hook will always trigger a rerender.

    If you want to prevent this, you can check if the count is already reset and don’t call it.

    import { Fragment, useReducer, useRef, useState,useMemo, useEffect } from "react"
    
    export default function Sample()
    {
        
       const [num,setnum]=useState({count:0})
       const inc =()=>{
       setnum((prevstate)=>({...num,count:prevstate.count+1}))
       }
       const reset = () => {
        console.log("render")
        if (num !== 0) {
        setnum({...num,count:0})
        }
       }
       return(
        <div>
        <button>{num.count}</button>
        <button onClick={inc}>Increment</button>
        <button onClick={reset}>reset</button>
        </div>
       )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search