skip to Main Content

I the next code I have this problem with Small component because always is print two time, even when the component is created first time

App.js

import { useCounter } from "../Hooks/useCounter";
import { Small } from "./Small";

export const Memorize = () => {
  const {counter, increment} = useCounter(10)

  return(
    <>
      <Small value={counter}/>
      <button
        onClick={event => increment()}>
        +1
      </button>
    </>
  )
}

useCounter.js
The counter value is working fine…

import { useState } from "react";

export const useCounter = (initialValue = 0) => {
  const [counter, setCounter] = useState(initialValue)

  const increment = (value = 1) => setCounter(counter + value)

  return {
    counter,
    increment,
    setCounter
  }
}

Small.js
… here the problem or I dont know…

export const Small = ({value}) => {
  console.log('Iam console log...');

  return (
    <small>{value}</small>
  )
}

… each time that I do click in button +1 this console is print:

Iam console log...
Iam console log...

… I try to envolve with memo but doesnt works…
any ideas ?

2

Answers


  1. React gives no guarantees about how often it calls the render method for a function during a render. If you read through the React documentation, they warn that this can happen. I wouldn’t be so concerned about it since React is still really fast

    One thing you can do is install the React dev tools for Chrome. Profile the code. React dev tools will show you the number and reason for re-rendering. Very likely, these two console.logs are part of the same render if this all the react code, and there won’t be much you can do about it.

    Login or Signup to reply.
  2. Probably because of the Strict Mode is on. Try remove in index.js.

    When <StrictMode> is enabled the component will render two times, that’s why its render two console.log()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search