I would suggest using the functional update form of setState if you don't have to access cnt inside useEffect, e.g. console.log(cnt). It lets us specify how the state needs to change without referencing the current state (docs):
importReact,{useEffect,useState}from"react";exportdefaultfunctionRefTest(){const[text,setText]=useState("");const[name,setName]=useState("");const[cnt,setCnt]=useState(0);// DOM handlersconstinputChangeHandler=({target})=>setText(target.value);constsendHandler=()=>setName(text);// HOOKuseEffect(()=>{setCnt(c=>c+1);return()=>{setCnt(c=>c+1);};},[name]);return(<div><inputtype="text"value={text}onChange={inputChangeHandler}/>
<buttononClick={sendHandler}>Send</button>
<div>Name:{name}</div>
<div>Count:{cnt}</div>
</div>
);}
This makes sense. I just used this code as an example to demonstrate the concept.. I will update the example later to be more specific. Like maybe if you had to send the count to the API call.
Thanks for the post!
I would suggest using the functional update form of setState if you don't have to access cnt inside
useEffect
, e.g.console.log(cnt)
. It lets us specify how the state needs to change without referencing the current state (docs):Alternately, if you don't need to display the count, use a
useRef
instead and save yourself a re-render.This makes sense. I just used this code as an example to demonstrate the concept.. I will update the example later to be more specific. Like maybe if you had to send the count to the API call.
I see your point. 👍