const React = /* Implement this */;
function HelloComponent(){
const [myNumber, setMyNumber] = React.useState(0);
// Simulate rendering data to a screen
console.log("My number:", myNumber);
// Simulate rendering a clickable button
const click = ()=> setMyNumber((num)=> num + 1);
return click;
}
React.mount(HelloComponent); // prints 0
React.simulateClick(HelloComponent); // prints 1
React.simulateClick(HelloComponent); // prints 2
React.simulateClick(HelloComponent); // prints 3
General idea being that the React item may be stateful, but the HelloComponent must be a stateless pure function.
How would you implement this?
Checking the function callers stops hooks from being composable, and doesn't work in strict mode. React is the only thing that calls a component function, so React can just remember the component it's rendering before calling the function. Also, associating a mounted component with the component function itself prevents the same component from being mounted multiple times, so I tweaked the example to more closely match how React associates a mounted component root with a DOM node. Here's a solution that addresses that: