React Counter with nested function as side effect dependency [problem]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from "react"; | |
const Logger = ({ index, getCounter }) => { | |
const [text, setText] = useState(""); | |
useEffect(() => { | |
const newText = `Contador ${index}: ${getCounter()}`; | |
setText(newText); | |
console.log(newText); | |
}, [index, getCounter]); | |
return <p>{text}</p>; | |
}; | |
const App = () => { | |
const [counterA, setCounterA] = useState(0); | |
const [counterB, setCounterB] = useState(0); | |
const getCounterA = () => counterA; | |
const getCounterB = () => counterB; | |
return ( | |
<div> | |
<Logger index="A" getCounter={getCounterA} /> | |
<Logger index="B" getCounter={getCounterB} /> | |
<button | |
onClick={() => { | |
setCounterA(prevState => prevState + 1); | |
}} | |
> | |
Incrementar contador A | |
</button> | |
<button | |
onClick={() => { | |
setCounterB(prevState => prevState + 1); | |
}} | |
> | |
Incrementar contador B | |
</button> | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment