useEffect in react: Everything you need to know

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:

No alt text provided for this image
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):

No alt text provided for this image

[Click to continue reading...]

To view or add a comment, sign in

More articles by Rajat Gupta

  • pseudo classes in css part 1 (:hover)

    Note: This is the first part of the series dedicated to the pseudo-classes of CSS. In this part, we'll understand the…

  • useContext in react: everything you need to know

    only understand this: Using useContext is not necessary, we use it to avoid prop drilling. Here's how prop drilling…

  • Sibling combinator in css

    There may be some confusion as what we are calling sibling. So, let's first get that out of the way.

  • rest parameter in javascript

    The rest parameter is introduced in ES6. It allows a function to accept an indefinite number of arguments as an array…

    1 Comment
  • PropTypes in react

    Let's see what reactjs.org has to say: As your app grows, you can catch a lot of bugs with type-checking.

  • What the heck are props in react

    Although we can make web apps using JavaScript. One of the reasons we are using react over JS is component reusability.

  • JavaScript: single-threaded and synchronous

    A few days ago single threaded and synchronous were just 2 heavy words for me. If this is you right now, don't worry…

    1 Comment
  • reduce() method in JavaScript

    Let's see what MDN has to say: The reduce() method executes a user-supplied “reducer” callback function on each element…

  • filter() method in JavaScript

    Definition by MDN: The filter() method creates a new array with all elements that pass the test implemented by the…

  • map() method in JavaScript

    Let's see what MDN has to say: The map() method creates a new array populated with the results of calling a provided…

Insights from the community

Others also viewed

Explore topics