useEffect in react: Everything you need to know
Only understand this: We use useEffect to do something after the view has been rendered. Now, let's get to code and make a simple counter to understand useEffect:
import {useState, useEffect} from 'react'
export default function App() {
const [counter, setCounter] = useState(0)
useEffect(() => {
console.log('from useEffect...', counter)
})
function incrementClickHandler() {
setCounter(counter+1)
console.log("Inside incrementClickHandler.....", counter)
}
console.log('before render...', counter)
return (
<div className='App'>
<h1>{counter} </h1>
<button onClick={incrementClickHandler}>Increment</button>
</div>
)
}
Here's the console result after the initial render (that is the increment button still not clicked):