0

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>
  )
}

Mauj Mishra
  • 133
  • 1
  • 12
  • What exactly is not defined inside the scope? – richytong Nov 27 '20 at 05:46
  • 1
    The above code works perfectly I just don't know how it works. In class components when we wanted to use any method we used to bind that to value of `this` so we can use the methods inside class when any event occurs. Because when events are called they are called differently and from my example the `handleClick()` is defined inside of `App()` so it is not available outside of `App()`. So how does `onClick()` access the `handleClick()`. – Mauj Mishra Nov 27 '20 at 05:51
  • 1
    setName is defined in a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) which binds it to the lexical environment of handleClick and can therefore be accessed inside the onClick callback. – Sam Gomena Nov 27 '20 at 06:14

2 Answers2

1

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.

Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31
0

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

Ketan Ramteke
  • 10,183
  • 2
  • 21
  • 41