JavaScript are this references in the body of callback functions resolved prior to method invocation when using arrow functions as callback functions? - javascript-objects

Trying to figure out how this references resolve to the lexical context when using arrow functions as callback functions. My suspicion is the this references in the body of the callback function are resolved before the method is invoked. I.e., before the arrow function is passed as an argument (rather than at each iteration for example if the method is forEach()). But I can't seem to find anything definitive on this. I did attempt to log the passed function but writing my own forEach() function thinking I could capture the difference between a passed arrow function and a passed non-arrow function. But the func parameter, converted to string for log purposes, revealed essentially nothing - show this still in the function (unresolved).

We can refer to the language specification that states that an arrow function gains knowledge of the value of this during its instantiation: https://262.ecma-international.org/12.0/#sec-runtime-semantics-instantiatearrowfunctionexpression

Related

Use Case for passing function as an dependency in useEffect in React

I started learning to react and came across the code snippet where the function was passed as a dependency array in useEffect. I want to know the use case where such function is being passed as the dependency and why do we need to pass the function as a dependency?
First: This only makes sense if the code in the useEffect callback uses the function. So let's take that as a baseline. :-)
Fundamentally, you'd do that so the code in the useEffect callback is using the most up-to-date version of the function.
Here are a couple of examples where that would be important:
The function is a prop. Since your code doesn't know why it got a new version of the function, it's important to re-run the effect with the up-to-date version of the function.
The function uses state information it closes over (rather than using the callback form of a state setter). If you didn't re-run the effect with the updated function, the function would use stale state information. (But I wouldn't do it that way. Instead, I'd have the function use the callback form of the state setter.)
There are likely others, but they all boil down to ensuring the effect uses the most recent version of the function.
I am also learning React and this article helped me understand functions in the dependency array of useEffect.
Functions in dependency array of useEffect
A function is an object. It has its own identity like an object. A component re-renders each time on of its state changes. When a component re-renders, the function which is defined inside the component gets a new identity.
I made a bit clear code example here. The example from the article was unclear for me to understand. Use the console tab to see the console logs.
It depends on the use of the useEffect and the definition of the function. Basically, if you put a function inside a useEffect array, each time the function will change, or more accurately, it's reference, your effect will be called again, with the new function reference.
This is good in case you want to always use the latest function, but it can also be tricky. If the passed function is defined inside a component, it means that on every component render the function will be redefined, meaning your effect will be called on each component render. It can be heavy sometimes, depends on what your effect does.
It can still be avoided though, if the component in which the function is defined is using useCallback in order to memoize the function. This way, the function will have its own dependencies array, and will only be redefined (and change reference) when you decide it's needed.

Why are functions invoked from event handlers considered "callback" functions? (React)

I am trying to wrap my head around the idea that a function called from an event handler like onClick is considered a callback function?
For example if I have "onChange={this.handleChange}" which calls a class function called handleChange(), why is handleChange a callback here? My understanding is that a callback is a function that is passed into ANOTHER function as a parameter? Am I missing something? Thank you.
this.handleChange does indeed get passed as an argument to a function, just not in your code. React takes care of calling domElement.addEventListener('click', this.handleChange) for you.
"Callback" is also a generic term for a function that is called when a given event occurs. Often these functions are passed in as parameters to other functions, because they allow the function being called to "notify" the caller when something happens. In this case, the event is the click, and the callback is the function executed when the click occurs.
My understanding is that a callback is a function that is passed into ANOTHER function as a parameter?
That is exactly correct. More generally it is a function that you pass to some other piece of code that will "call back" to your function when something happens.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action
The above is from MDN web docs.
Since the function is being called in response to an event being detected, it is passed as an argument to event handler. An event handler is a function called when an event (click) happens.

Why sometimes I see an arrow function and other just the the function on event handlers in react?

Sometimes I see this on a react handler:
<Results onClick={() => this.somefunction()}/>
and other times like:
<Results onChange={this.handleChange} />
What is the mail difference on these ways of writing the code?
In your first example somefunction doesn't need to worry about having access to the wrong this: it will refer to the instance of the class that's defined in.
Your second example may not have the same certainly, depending on how's defined: you will need to bind the function or use arrow functions.
The actual react documentation provide more insight on this: https://reactjs.org/docs/handling-events.html
Also: referential identity. The first example create a new function on every render. It may mess up with pure component, because the props will keep changing. The second example pass always the same function: pure component will see them as the same props as before and won't re-render unnecessary.
The former 'hoists' the someFunction in a callback to be ran at a later time. The latter looks for the code in handleChange immediately.
Also, you have the context issue with this. In an arrow function, this doesn't attach context to the function itself, but rather to the parent context. In essence, this would have the same context in each of these examples.

Why to pass function reference instead of method in onClick event of button in ReactJS?

Whenever I pass function parentheses in onClick of button, it automatically calls when page loads even without clicking on button.
But when I don't pass function parentheses in onClick of button, it calls only when button is clicked.
With passing parentheses in function call
<button onClick={this.handleButtonClick()}>Increment</button>
Without passing parentheses in function call
<button onClick={this.handleButtonClick}>Increment</button>
Why function called automatically on page load whenever I pass parentheses to function even-though it is written inside onClick of button ?
There's a difference between a function call and a function.
When a component renders, all statements are executed and expressions are evaluated. It's plain javascript, that's how javascript works.
this.handleButtonClick() is a function call, and therefore the function will be called once the component renders. I assume that handleButtonClick() returns undefined which will cause the button to render as <Button onClick={undefined} />. Now, if onClick is undefined, nothing will happen when the click actually happens as there is no function to be called.
this.handleButtonClick is just a reference to a function, it doesn't invoke it. You need to pass the function reference to onClick prop so that it can be called later by React, once the click actually happens.
It automatically calls because you are invoking it immediately by:
this.handleButtonClick()
"onClick" does not work like that, if you want to manually invoke the function you can use:
onClick={() => this.handleButtonClick()}
This is done automatically if you use function reference. Hence, you don't need to invoke it or use a callback function. Actually, using function reference is better since that function isn't recreated in every render.
There is a difference between function reference and function invoking.
When you set the dynamic value like:
this.handleButtonClick()
that means you're invoking the function as soon as the component renders to the page.
But when you just pass the reference of the function like
this.handleButtonClick
that means React will call this function only when the user clicks on it.
JS will execute the function On each Render when you do OnClick(Func(params))
because you are calling a function instead of passing it.
Do this instead :
OnClick ( ()=> {Func(params) } )
In react functional components, if we pass any function to onclick this way.. onClick={func()} this func will be called right away when the page is loaded, that for sure we don't want.
So we have two ways to make it work right.
one, pass it as a reference like this- onClick={()=> func()} (this means only pass reference to that function when page loads, but call that func() if component is clicked over.)
second, just pass the name of the function- onClick={func} (this means both pass reference and call on Call).
these both things work the same way. second one is more easy however the former one is used the most.

What is a react callback in scalajs-react?

Here it is written:
Included is a type CallbackTo[A] which captures effects designated for
use in React callbacks.
What is a React callback in this context ?
As far as I know, just the normal meaning of callback - a function that is called in response to an event. So for example in a React Component there are many functions like componentDidMount that are called at different stages in the lifecycle of the component. In scalajs-react these are implemented as functions that return a CallbackTo[Unit], which can also be written as Callback due to a type alias. For example when adding a componentDidMount callback to a ReactComponentB, we use def componentDidMount(f: DuringCallbackM[P, S, B, N] => Callback): ReactComponentB[P, S, B, N].
In javascript a component is expected to just immediately run any side-effects of the event, in the componentDidMount function (or the other callbacks). In scalajs-react, the component instead wraps these effects in a Callback, and returns that. This allows for the scalajs-react system to delay actual execution of the code in the Callback - this is done later by calling runNow(). This also means that Callbacks are combined using map, flatMap, >> etc. They will not run unless runNow() is eventually called, so if you are not returning a Callback to some other code to execute later, just creating it will do nothing.
There's much more about Callback in the docs.

Resources