2 ms·
This would make for an interesting exercise. const React = /* Implement this */ function HelloComponent(){ const [myNumber, setMyNumber] = React.use
by rashkov 6y ago
This would make for an interesting exercise.
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 can it draw on React's statefulness, while only using that useState() call?
I am working through this exercise now, but I'm already finding myself doing some pretty hacky things to make this work (like finding out who called a function using arguments.callee.caller.name). Still, it's pretty interesting.
Edit: My solution to this: https://gist.github.com/rashkov/f765917d09ebd629f385c21195f42b4c https://gist.github.com/rashkov/f765917d09ebd629f385c21195f4...
- AgentME 6y agoChecking the function's caller breaks the composability of hooks: it stops hooks from being called by other hooks. (Also, it doesn't work in strict mode, which is enforced when you use ES modules.) React is the only thing that calls component functions, so React can just remember what component is being called before it calls it. I've posted a reply on your gist with an example that addresses this.
- rashkov 6y agoVery cool! appreciate the response, very interesting to see an improved solution on this. I was mainly interested in solving for how React lines up the useState calls with the actual data that it's keeping under the hood. So I definitely cheesed through the parts touching on how React keeps track of the component tree. I'm enjoying reading through your interpretation of this though. Thanks