Reputation: 1327
I am learning Reactjs. And I am building Counter App. I think the code below and state in react are the same. console.log print correctly but in the html it doesn't change the value. Can you explain to me why the code didn't work?
import React, {useState} from "react";
let count = 0;
const Counter = (props) => {
const setCount = ()=> {
count = count + 1;
};
return (
<div>
<button onClick={()=> {
setCount();
console.log('counter: ', count);
}}>button</button>
<div>Hello {props.name} and your current number is: {count} </div>
</div>
)
};
export default Counter;
Upvotes: 0
Views: 65
Reputation: 1154
First of all, according to React docs, a component re-renders only when a state
or a props
(used in the component) updates. So change in a variable doesn't affect the rendering of the component. If variable change affects the component, then there would be no need of using this library. Learn about setState. Hope it helps!.. Happy coding! ..
Upvotes: 2
Reputation: 860
Well.. that's why state is there for.. It essentially tells your component to REACT, to its change.
If you want your DOM to respond to the change of a variable, You need to bind it to a state variable.
Your code below, will only change the variable, but won't trigger any re-rendering. That's why you could see the change in console, but not in DOM.
const setCount = ()=> {
count = count + 1;
};
Upvotes: 2
Reputation: 22513
To see updates in the dom you must rerender a component. There are a few ways to do this.
if you put the count variable in a state and trigger it from there you will see it update in the component
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Upvotes: 3
Reputation: 224
html should be rendered with the new value once button is clicked, this is where the state and setstate methods comes to play. setcount means setcount will change the value and refreshes or say rerender the html with the value.
Upvotes: 2