I am making a simple react counter, where on click INC button the value should change the value inside h1. But it is not working.
My code in App.js:
import React from "react";
import "./styles.css";
export default function App() {
let count = 0;
function handleInc () {
return count++;
}
return (
<>
<div>
<h1>{count}</h1>
<div className='container'>
<button onClick={handleInc}>INC</button>
<button>DEC</button>
<button>RESET</button>
</div>
</div>
</>
);
}
Her is my sandbox link:
You aren’t changing anything, that’s not how Javascript works.
- function executes
-
count
free variable is set to 0
- a function
handleInc
is defined, which adds one to the value of count
, returning that value.
- the function returns the JSX: what that eventually produces is an HTML node with the text in
<h1>
set to the value of count
(so 0).
- it doesn’t matter if you change the value of
count
– the function has already returned the result, and in that result count
is 0
- you can’t change the value a function returns after you’ve returned it, that makes no sense.
- you can rerun the function with some change to the parameters and produce a different result – this is what React does when you use state/props and the [de facto standard] function API.
- you can use a data structure that is packaged with methods that operate on that data (ie a class), which is what the React class-based API does.
To retain the state, it has to be stored somewhere outside the function – this is why React uses state (and props to pass values into components). What you’ve written can’t work.