Reputation: 1333
I am new to Reactjs and trying to do some simple stuff. In the below code snippet I have declared two state variable counter
and setCounter
to 9
but when I am rendering both of them in the UI {setCounter}
is not getting rendered whereas I am able to see 9
in the UI which is the {counter}
import * as React from 'react';
const {useState} = React;
export default function App()
{
const [counter, setCounter] = useState(9); // Declaring State variables
return (
<>
<p>{counter}</p>
<p>{setCounter}</p>
</>
)
}
Please suggest where I am doing wrong.
Upvotes: 0
Views: 49
Reputation:
Hey friend I recommend you to see the React documentation, since it is just starting, check it out on the subject of states. As for what you are doing, the first thing setCounter is not a variable, it's a function that changes the value to the variable counter, counter is a variable that you can call in any part of your component or you can even send through the props to other components. Hopefully you have served this little help, but it is never too late to start with the time you will dominate friend. Thank you very much.
Documentation link: https://reactjs.org/docs/hooks-state.html
Upvotes: 1
Reputation:
setCounter is a function. Let me explain how this works. I drafted up a function based on the example you provided.
import React, { useState } from 'react';
export default function App() {
const [counter, setCounter] = useState(9); // Declaring State variables
const addOne = () => {
if (counter === 9) {
setCounter(counter + 1)
};
}
return (
<>
<button onClick={() => { addOne() }}></button>
<p>{counter}</p>
</>
)
}
I created a function where I take the 9 that you assigned and set the counter to that value, and increment by one. Then in the return, I created a button. When clicked, the button will call the addOne function and setCounter to increment by one. I hope this illustrates the difference here and why you won't be able to simply render setCounter.
Upvotes: 1