How can i make a simple counter in React without using state

Viewed 1588

I'm trying to make a simple app that counts the number of times the button has been clicked. I read this is a good first question in JS interviews. "Ask the candidate to build a click counter using any popular framework (React preferred in 2020). This ridiculously simple app has one job: keep track of how many times the user has clicked the button during the current session. No storage. No network I/O. Just count clicks. It is intentionally ridiculously simple" My first instinct would be to use hooks, but the question wants the programmer to do it without using storage which I believe includes using state.

import React from 'react';
import './App.css';

function App() {

 let count=0;

 const add=()=>{
    debugger;
    count++;
  }

  return (
      <header className="App-header">
      <button onClick={()=>add()}>click me</button>
      {count}
      </header>
  );
}

export default App;

Here is what I tried. Using debugger I can see count does go up but the changes aren't showing on the page. Any advice would be appreciated.

2 Answers

React is a JS library so we can use pure js:

function App() {
  return (
    <div className="App">
      <h1 id="c">0</h1>
      <button
        onClick={() => {
          let c = document.getElementById("c");
          c.innerHTML = parseInt(c.textContent)+1;
        }}
      >
        +
      </button>
    </div>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

The reason your code doesn't produce the expected result is that React doesn't update the dom unless it sees that an update is necessary, i.e., because the state of the component changed.

So, in your case, the component only gets rendered once, when the value of count is 0. If you want to React to re-render the component and show you the new value, you'll have to trigger that with a state change. Alternatively you can follow cybercoder's solution, which actually opts out of React by supplying its own innerHTML.

Related