Often when writing a component in React+Typescript, I want to trigger a useEffect hook on one of the props. For example, consider a button that executes a different function for each consecutive mouse click:
export function ActionButton({clickActions}: {clickActions: (() => void)[]}) {
const [clicked, setClicked] = useState(0);
useEffect(() => {
if (clickActions.length > 0 && clickActions[clicked % clickActions.length]) {
clickActions[clicked % clickActions.length]();
}
}, [clicked, clickActions])
return <button onClick={() => setClicked(clicked => clicked + 1)}/>
}
In this case, clients of this component, need to be aware that they somehow need to prevent clickActions from being a different instance on every render. For example, it could simply be a constant, or be memoized by using useMemo.
Is there a best practice for making my clients aware of this? Are there ways to trigger compile time errors when this rule is violated?
NOTE: I realize this particular case can be solved without using useEffect, but it's just a simple example to illustrate the pattern. I'm not interested in solving this particular problem, but in how to solve the general problem.