Reputation: 183
I am learning react.js functional components and I came with the method useState()
. Which gives an array in return [currentState, stateSetter]
. Now if we use stateSetter()
in an event. And we know that events are called differently. So how does it access the handleClick()
function. Since it is not defined inside the scope?
import React, {useState} from 'react';
function App(props) {
const [name, setName] = useState("name1");
const handleClick = () => {
setName("name2");
}
return (
<div>
<p>Hello, {name}</p>
<button onClick = {handleClick}></button>
</div>
)
}
Upvotes: 0
Views: 1687
Reputation: 5613
It's simple because your are passing to the onClick
function a reference to the function which you have define and save as value of variable named handleClick
. As long as JS can resolve the reference of that variable the function or the value which that variable references will be executed.
That is the same with classes Component when we pass this.handleClick
to an onClick
props of a tag, we are just passing the reference to that function.
Upvotes: 1
Reputation: 10675
Because unlike Class bases components functional components do not have instance so there is no need to use this or binding functions inside it while using.
Here is another answer you might want to check out: functional component
Upvotes: 0