Yes, I know this question have been asked zillion times, but none of the answers are fit to my code.
My useEffect()
calls an outside function (showIncrement()
) that logs my increment
state value. The problem is showIncrement()
is also used by a button, so I can't move it inside the useEffect()
scope.
I know a few solutions to this:
- re-create the function inside
useEffect()
, but then I have two identical functions - use the React
useCallback()
function, React documentation call it the last resort, and other answer in another question also don't recommend using it, so I'm not really sure
The question is, what is the best way to solve this problem? Is it safe to use useCallback()
?
Here's my code:
const App = () => {
const [increment, setIncrement] = React.useState(2);
const showIncrement = React.useCallback(() => console.log(increment), [
increment,
]);
React.useEffect(() => {
showIncrement();
}, [showIncrement]);
return (
<div className="App">
<button type="button" onClick={showIncrement}>
Show Increment
</button>
</div>
);
};