I am new to React js and I am implementing the useEffect for the first time in my code. I followed few tutorials and they have done things differently as follows
Case l:
function App() {
const[counter,setCounter] = useState(0);
const[toggle,setToggle] = useState(false);
const incrementer = () =>{
// counter+=1
setCounter(counter + 1);
console.log(counter)
};
const toggler = () =>{
setToggle((toggle) => !toggle);
};
return (
<div className="App">
<h1 className = {toggle ? 'active' : ''} >Hello world!!</h1>
<h1>{counter}</h1>
<h1>{abc}</h1>
<button onClick={incrementer} >Click</button>
<button onClick={toggler}>Toggle Here</button>
<div className="home">
<h1>{Date.time}</h1>
<Nav/>
<Tweets/>
</div>
</div>
);
}
Here inside the incrementer function, I am just using counter+1 and it gives the required result and makes sense. It increases the count by 1 on every click.
Now case 2:
function App() {
const[counter,setCounter] = useState(0);
const[toggle,setToggle] = useState(false);
const incrementer = () =>{
setCounter(() => counter+1);
console.log(counter)
};
const toggler = () =>{
setToggle((toggle) => !toggle);
};
return (
<div className="App">
<h1 className = {toggle ? 'active' : ''} >Hello world!!</h1>
<h1>{counter}</h1>
<h1>{abc}</h1>
<button onClick={incrementer} >Click</button>
<button onClick={toggler}>Toggle Here</button>
<div className="home">
<h1>{Date.time}</h1>
<Nav/>
<Tweets/>
</div>
</div>
);
}
In this case, inside the incrementer function, it is using what seems like an arrow function. I assume it is using function inside the function. Also, it is not passing anything as () is empty. How the count is increasing here. I am confused.
Also inside the toggler function, I can write abc or any variable instead of toggle and it works. How??
Update
Ok my main confusion is in this code.
const incrementer = () =>{
// counter+=1
setCounter((kkk) => kkk + 1);
// setCounter(() => counter+1);
console.log(counter)
};
This function works as well. How is this kkk value is getting the value of counter=0. Shouldnt we be writing counter instead of kkk??