is it okay to do this in react, to put the event handlers and other functions that depend on useState outside the component? to avoid wrapping my functions in useCallback
like with this example:
import { useState } from "react";
const handleClick = (fn) => fn((prev) => prev + 1);
export default function App() {
const [val, setVal] = useState(0);
return (
<>
<p onClick={() => handleClick(setVal)}>clicked {val}</p>
</>
);
}
2
Answers
The useCallback hook ensures that handleClick is memoized and won’t be recreated on every render unless its dependencies change.
Since React optimizes the re-render process by memoizing function references, you are implicitly using memoization. [wikipedia]
As long as the function stays pure and stateless, it will not be recreated upon each re-render.
You can even export it from a separate module and then import the pure stateless functions you want to make use of.