Skip to content

Instantly share code, notes, and snippets.

@megatroom
Created Feb 13, 2020
Embed
What would you like to do?
React Counter with nested function as side effect dependency [solution 2]
import React, { useState, useEffect, useCallback } 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);
// Condiciona a recriação da função só quando o contador for alterado
const getCounterA = useCallback(() => counterA, [counterA]);
const getCounterB = useCallback(() => counterB, [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