0
import React, { useReducer } from 'react'

const reducer = (state, action) => {
  console.log(action.type);

  switch (action.type) {
    case 'inc': return state + 1
    default: return state
  }
}

function App() {
  const [counter, dispatch] = useReducer(reducer, 0)

  const countUp = () => (
    dispatch({ type: 'inc' })
  )

  console.log('render');

  return (
    <div>
      <h2>{counter}</h2>
      <button onClick={countUp}>Count up</button>
    </div>
  )
}

export default App

Why when i click on Count up button (App component) re-render and log 'render string' to the console twice?

Is that a normal behavior?

skyboyer
  • 22,209
  • 7
  • 57
  • 64

1 Answers1

0

I don't think it actually renders twice since when placed in a useEffect like

useEffect(()=> console.log("render") )

it only gets called once, and useEffect is the equivalent of componentDidMount.

Pavlos Karalis
  • 2,893
  • 1
  • 6
  • 14
  • yeh, useEffect dose not case a problem, but i found when i use React.StrictMode component in index.js file which create-react-app is used by default it is casing re-render when i use useState, useMemo, useReducer, shouldComponentUpdate in class component, setState | i found the answer in here =>> https://stackoverflow.com/questions/61578158/why-does-usestate-cause-the-component-to-render-twice-on-each-update – Mustafa Wael Jun 29 '20 at 21:15