Hacker News new | ask | show | jobs
by rashkov 2116 days ago
Thanks for the idea. I've formulated a small version of this problem as follows, and provided a solution elsewhere in this thread:

  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
1 comments

this is a pointless example. it doesn't render anything, and therefore doesn't have to deal with React's render cycle.

also, you shouldn't use useState unless you want it to rerender, which you don't because you're printing to console. use a ref instead for myNumber.

the problem you are trying to solve, updating a number if someone clicks on something, is already solved in React:

    const HelloComponent => React.forwardRef((props, forwardRef) => {
     const myNumber = useRef(0)
     const printToConsole = () => {
        myNumber.current = myNumber.current + 1
        console.log("My Number:", myNumber.current)
      }
      render (
        <div ref={forwardRef} onClick={printToConsole}>click me</div>
      )
    }
then you can simply trigger a click by calling .click() on the forwarded ref wherever you happen to mount it.