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

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.

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.

Are props.render and props.children equal?

I can't find a distinction between props.render and props.children, so I'm starting to believe that they achieve the same thing BUT in different ways.
Is this a correct assumption? If not; how are they different (beside how they are implemented), and when should I use one over the other?
render-props can address your questions.
children is part of the Top-level API, meaning, it is intrinsic to a react component. The children prop can be just about anything react can render, typically an element or array of elements, but can be a function similar to a "render prop".
The "render" prop, however, is not intrinsic, it can be anything really... so long as it is a function.
Using props other then render
It’s important to remember that just because the pattern is called
“render props” you don’t have to use a prop named render to use this
pattern. In fact, any prop that is a function that a component uses to
know what to render is technically a “render prop”.

React hooks: is `useCallback` not so needed usually?

I am recently refactoring a web app using React Hooks. I encounter a problem regarding useCallback. Based on description of Kent: https://kentcdodds.com/blog/usememo-and-usecallback, useCallback is to pass in identical function reference to sub-components, to avoid re-render of sub-components, so that the performance is better. However, it's used together with React.memo. And as Kent said:
MOST OF THE TIME YOU SHOULD NOT BOTHER OPTIMIZING UNNECESSARY RERENDERS. React is VERY fast and there are so many things I can think of for you to do with your time that would be better than optimizing things like this. In fact, the need to optimize stuff with what I'm about to show you is so rare that I've literally never needed to do it ...
So, my question is: am I right to claim that we do not need to use useCallback usually? except when the callback is expensive to create, using useCallback avoids re-creating the callback for every render.
Say, for a onClick or onChange event handler, 2 lines or less, shall we just not use useCallback to wrap it?
I find the useCallback() is necessary when I don't want the function reference to change. For example, when I'm using React.memo on some child component that should not be re-rendered as a result of a reference change in one of its methods that comes through props.
Example:
In the example below Child1 will always re-render if Parent re-renders, because parentMethod1 will get a new reference on every render. And Child2 will not re-render, because the parentMethod2 will preserve its reference across renders (you can pass a dependency array to make it change and be re-created when new input values come).
Note: Assuming the Child components are being memoized with React.memo()
function Parent() {
const parentMethod1 = () => DO SOMETHING;
const parentMethod2 = useCallback(() => DO SOMETHING,[]);
return(
<React.Fragment>
<Child1
propA=parentMethod1
/>
<Child2
propA=parentMethod2
/>
</React.Fragment>
);
}
On the other hand, if the function is expensive to run, you can memoize its results using the useMemo hook. Then you will only run it when new values come, otherwise it will give you a memoized result from previous calculations using those same values.
https://reactjs.org/docs/hooks-reference.html#usecallback
useCallback
Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate).
useMemo
Pass a “create” function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.
I think you are right. From how it's designed, useCallback should be almost useless in React. It can not be used directly to prevent a child render.
What can save a child render is to wrap entire render using a useMemo.
const Title = () => {
...
const child = useMemo(() => {
return <Child a={"Hello World"} />
}, [])
return (
<>
{child}
<div onClick={onClick}>{count}</div>
</>
)
}
The above approach is a bit different than React.memo because it acts directly on the parent Title, instead of Child. But it's more or less answer your question why it's useless, except when you use it as the shortcut for useMemo.
Article explaining this, https://javascript.plainenglish.io/can-usememo-skip-a-child-render-94e61f5ad981
back to useCallback
Now let's go back to see if a callback wrapped with or without useCallback is useful.
<div onClick={onClick}>kk</div>
The only thing it might save is that when it's under reconciliation, onClick (with useCallback) points to the same function instance.
However I don't know if React actually does any optimization at that step. Because assigning a different callback to the attribute might take additional memory and time. But adding a new variable in general takes additional memory as well.
So this type of optimization is more like a coding optimization, more or less subjective. Not objective enough to be applied in a solid case.
Of course, if you want to fix a function instance for any third party function, ex. debounce. That might be a good use, but still smell fishy, because useMemo seems much more versatile to cover this case as well.
All in all, I'm only pointing out, useCallback isn't doing what's the public believe it can do, such as to bailout child component.

What is the difference between using a method or a function outside React component

Recently i found a React component that uses a function outside the component in a onClick attribute. The reasoning behind that is that, and i quote: "it is better to use a function outsite the React component when there is not need to use this context". I personally don't find that answer very satisfying.
You can find a codesanbox example here
There's any real difference? maybe in performance?
Thanks!
You must effectively write function outside of component if you don't need "this" context. The benefits is that the outside function is instantiated only one time and shared by all the component instances.

Should "component" functions in Om be called directly?

As I'm only starting to fully understand, om.core/build and om.next's factory functions return React element objects, which refer to component functions/classes, and the actual component is only instantiated later by React's reconciler. That is, (om.core/build some-component data) doesn't actually call some-component immediately.
However, we often represent simple, "stateless" components as just functions which take props and return a React element. In the (pure) React world, you'd use one of these functions like a component class, as React.createElement(AStatelessComponent, {some: "props"}), or more conveniently in JSX as <AStatelessComponent some="props" />. Those too return a React element which references AStatelessComponent, which won't actually be called until later.
But in Om, when we have a simple component like this (and by "we" I mean me and my team, at least), we call the function directly. Thus,
(render [this]
(om/div {}
(a-stateless-component {:some "data"})))
Here, a-stateless-component is called immediately, and whatever it returns is inserted directly into the div, rather than being substituted later by the React reconciler.
Is there a preferred way to React.createElement in Om? Or is it preferred to just call functions like this directly, even though it skips creating a component instance in the render tree?
In Om, if you want to instantiate a stateless component you need to call js/React.createElement directly.
Why you would want to do that depends:
if you call React.createElement you get a "tracked" instance in React's reconciler
if you don't, you get inlining but the stateless component now cannot be distinguished from its parent in React's render tree.
EDIT: I just realized that om.next/factory is permissive enough that it allows you to instantiate the stateless components you were talking about. So you can achieve what you want both by calling js/React.createElement directly on a function of props, or by calling om.next/factory with that same function as argument.
Here's a working example. The following code:
((om/factory #(dom/div nil "Hello, World")))
results in the following component (in React's devtools):

Resources