Using method on class or function in closure - javascript

Say I want to create a Simple React component with some methods (no state or life-cycle methods). I can do it one of two ways:
// Foo.js
class Foo extends React.Component {
doSomething() {
// do something
}
render() {
...
this.doSomething();
...
}
}
export default Foo;
Or I can do it like this:
// Foo.js
const doSomething = () => {
// do something...
}
const Foo = () => {
...
doSomething();
...
}
export default Foo;
The second is preferable because it's a functional component (simpler, less overhead), but does the closure function come with any overhead / risk of memory leaks?
In general, if a component doesn't keep state or use life-cycle methods, which is the preferable way to implement the component?

Generally, if you:
Do not want to maintain state
Don't need to use lifecycle methods ( like componentDidMount )
it's better to use stateless functional components, which are fast and more readable. And no, you needn't worry about memory leaks due to closure. For more benefits of stateless components, see https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc

There is no need to use class-based components if you are not keeping track of application state or life-cycle methods simply because it is a lot of overhead, and you don't need to keep track of the this keyword, which is frankly, annoying.
A functional component is dumb. It has no idea of the application state at all. It can be used to display / present the component without having to worry about updating itself when an event is emitted.
In your case, if the doSomething() method does not involve any dynamic behavior, it is preferable to go with the second approach.

Related

How to pass the set[State] function to a non-descendent trigger component

Here is the diagram. ChildComponentB has a state - stateX. In ChildComponentA, once the event occurs, it will change the stateX in ChildComponentB.
If the ChildComponentA is the child component of ChildComponentB, then it's easy, just pass the setStateX as a prop to ChildComponentA. But in this case, it's not.
The real scenario is the following. I have a canvas component, there are some static Rectangles already there, once there are mouse move over the line of the Rectangles, I'd like to add the indicator lines to another child component of the canvas component.
Hence, the rectComponent is not the descendent of the distanceIndicatorsComponent. So I can't pass the setLines to RectComponent.
What's your approach to do that?
If I use useContext approach, will it work?
Thank you, #KonradLinkowski to provide your solution. Here is his code. However, useContext is still lifing the state up to ParentComponent.
import React, { useContext, createContext, useState } from "react";
const Context = createContext();
function ChildComponentA(props) {
const { setStateX } = useContext(Context);
return (
<div>
componentA button:{" "}
<button onClick={() => setStateX((i) => i + 1)}>add</button>
</div>
);
}
function ChildComponentB(props) {
const { stateX } = useContext(Context);
return <div> stateX is {stateX} </div>;
}
export default function ParentComponent(props) {
const [stateX, setStateX] = useState(0);
return (
<>
<Context.Provider value={{ stateX, setStateX }}>
<ChildComponentA> </ChildComponentA>
<ChildComponentB> </ChildComponentB>
</Context.Provider>
</>
);
}
Regarding the reusbility of the ComponentB i.e. distanceIndicatorsComponent in this scenario, it includes the JSX and the states plus the interface in which there are logic to change the states. The are all parts which should be reusable in the furture.
From OOP perspective, the lines (state) belongs to DistanceIndicatorsComponent, and the how to change the lines (Add Line in this case) should be also reusable logic which belongs to distanceIndicatorsComponent.
However, from React perspective, to lift the setLines (this is the interface triggered under some event) is not "good enough" from OOP perspective. To lift the state - lines and state management function - setLines up to CanvasComponent is a "not good enough" in terms of the encapsulation. Put a wrap component on top of ComponentB is the same thing, the setLines still can't be passed to FrameComponent unless FrameComponent is a child-component of the wrap component.
It's very common to see there is a very heavy component holding all the state and the events at the top. It makes me feel that's a bad smell of the code. The reusability of the component should be based on a set of components, in this set of components, there is one uncontrolled component at the top, and underneath of this uncontrolled component are controlled components. This set of components is a external reusability unit.
Here, in this diagram, there should be more than one reusable unit rather than one. If lift the state up to CanvasComponent, it makes all the components underneath are un-reusable. In some extents, you still can re-use the JSX of this component, but I'd say, in terms of reusablity, it should invovle as many reusable logic as possible.
I might be wrong, please correct me. And thank you for sharing your valuable comments.
Requirements
First let us sum up the requirements.
Rect Component and Distance Indicators have not much to do with each other. Making them aware of each other or creating a dependency between them would be not desired in a good OOP design.
The interaction between both is very specific. Establishing a mechanism or a data structure just for this special sort of interaction would add an overhead to all components that don't need this sort of interaction.
General Concepts
So you must use a mechanism that is so generic that it does not add any sort of coupling. You need to establish something between these two components, which only these two components know and which for all the rest of your program is nonsense. What mechanisms serve for such a purpose?
Function pointers
Lambda functions
Events
Function pointers and lambda functions are complicated constructs. Not everybody prefers to use them. Now you see why events are so popular. They address a common requirement of connecting two components without revealing any of the details of them to anybody.
I personally recommend you to use lambda functions in this situation. Because this is one strength of JavaScript. Search in google for callback or asynchronous lambda function. This often adds the least overhead to existing code. Because a lambda functions has an important property:
With lambda functions you can do things very locally. Doing things locally is an important design principle. You don't need to define extra methods or functions or classes. You can just create them wherever you are, return them, pass them freely around to where you actually need them and store them there. You can store them even without knowing what is behind them.
I think, this is your answer. The only thing you need is a mechanism to pass lambda functions and to store your lambda functions. But this is on a very generic level and therefore adds no coupling.
With events you are on similar path. The event mechanism is already there. But therefore you already have a good answer.
Example with pure JavaScript
When applying this to JavaScript we can imagine that function pointers could be compared to function expressions in JavaScript. And lambda functions can be compared to arrow functions in JavaScript. (Note: Arrow functions also provide "closures", which is required in this case, see How do JavaScript closures work?).
A simple example illustrates this:
class DistanceIndicator {
constructor(height, width) {
this.height = height;
this.width = width;
}
resize(height){
this.height = height;
}
incorrect_resizer(height){
return this.resize;
}
resizer(){
return (height) => this.resize(height);
}
resizer_with_less_overhead(){
return (height) => this.height = height;
}
}
p = new DistanceIndicator();
p.resize(19);
// If you want to use this, you have to store p. You may see
// this as not so nice, because, you are not interested in what
// actually p is. And you don't want to expose the information
// that it has a method resize. You want to have the freedom
// of changing such details without the need of changing all
// the code where something happens with Rectangles.
console.log(p.height);
resizer = p.incorrect_resizer()
//resizer(18);
// In this example, resizer is a function pointer. It would be
// nice to store it and be able to call it whenever we want to
// inform Rectangle about something interesting. But it does not
// work because the resize method cannot be isolated from the
// class. The "this" is not there.
console.log(p.height);
resizer = p.resizer();
resizer(17);
// That works. Lambda functions do the job. They are able to
// include the "this" object.
console.log(p.height);
resizer = p.resizer_with_less_overhead();
resizer(16);
console.log(p.height);
// As you have now a resizer, you can store it wherever you want.
// You can call it without knowing what is behind it.
The idea in the example is that you can store the resizers wherever you want without knowing what they are. You shouldn't name them resizer, but give them a generic name like size_notification.
Example for React
The React concept for contexts is a typical candidate for data exchange between components. But the principle of React is a pure unidirectional data flow (top-down). This is also true for the context, which means, we cannot use a context for what we want.
React does not provide support for the implementation of the proposed idea. React is only responsible for the pure construction of the HTML page and a comfortable and performant rendering. It is not responsible for the "business" logic of our HTML page. This is done in full JavaScript. That makes sense because you want be able to develop complex web applications. Therefore you need all your favourite programming concepts. A real application does not follow the design principle of React. React is only a presentation layer. Most people like OOP progamming.
So when implementing something with React we must keep in mind that React is just a library for JavaScript. The full power of JavaScript is always available and should be used for our web application.
After realizing this, the problem becomes simple. See this code:
import React from 'react';
let sizeNotificator = (newValue) => {console.log(newValue)};
function Rect(props) {
return <button onClick={() => sizeNotificator("12")}>resize to 12</button>;
}
class DistanceIndicator extends React.Component {
state = {
size: "0",
};
setSize(newValue) {
this.setState({
size : newValue
});
};
componentDidMount(){
sizeNotificator = ((newValue) => {this.setSize(newValue);})
}
render() {
return <p>Current size: { this.state.size}</p>;
}
}
class App extends React.Component {
render() {
return(<div>
<DistanceIndicator/>
<Rect/>
</div>);
}
}
export default App;
With this code the requirement is fulfilled that none of the DistanceIndicator implementation details are revealed to the outside of DistanceIndicator.
Obviously this example code only works if there is not more than one DistanceIndicator. To solve this is a different topic with probably not only one good solution.
If keeping the shared state in the ParentComponent is the problem, you can extract the Context.Provider to a separate component and pass components as it's children, those children can access the context value via useContext hook.
function ParentContextProvider({ children }) {
const [stateX, setStateX] = useState(0);
return (
<Context.Provider value={{ stateX, setStateX }}>
{children}
</Context.Provider>
);
}
export default function ParentComponent(props) {
return (
<ParentContextProvider>
<ChildComponentA />
<ChildComponentB />
</ParentContextProvider>
);
}
Now you can add any new state/setState to the ParentContextProvider and can pass it to it's children
Have you looked at Redux stores? You could have a variable like "showLine" or "originX"/"originY", then have one child dispatch changes, and the other child useSelector for the values?
Do you know if Redux works for your use case?
I prefer to use a simple events pattern for this type of scenario. Eg using a component such as js-event-bus.
CHILD COMPONENT A
props.eventBus.emit('MouseOverRectangle', null, new MyEvent(23));
CHILD COMPONENT B
useEffect(() => {
startup();
return () => cleanup();
}, []);
function startup() {
props.eventBus.on('MouseOverRectangle', handleEvent);
}
function cleanup() {
props.eventBus.detach('MouseOverRectangle', handleEvent);
}
function handleEvent(e: MyEvent) {
// Update state of component B here
}
RESULTS
This tends to result in quite clean encapsulation and also simple code. Eg any React conponent can communicate with any other, without needing to reveal internal details.

Converting React ES6 class to functional component - what to use for private methods?

I'm converting a React ES6 class-style component to a functional component. The one thing I'm slightly unsure of is how best to convert private class methods. As far as I can tell, I should convert them to functions within the functional component's function, as they need to be there to access the component's state. However, that presumably means that on each re-render, the function is going to get recreated:
Before
class Game extends React.Component {
handleClick(i) { if (this.state.foo) { ... } }
}
After
function Game {
function handleClick(i) { if (foo) { ... } }
}
Is this a problem performance-wise, and if so, is there any way to improve it?
Also, most guides I've read recommend assigning arrow functions to variables instead of just declaring functions, eg.
function Game {
const handleClick = (i) => { if (foo) { ... } }
}
Is this purely stylistic, or is there another reason to use assigned arrow functions over regular nested function definitions?
You can use functions defined with either the function keyword or the arrow function syntax. It does not really make a difference in this case. However, with the arrow syntax, functions do not get hoisted, and that may cause the linter to report a warning if you use a function before it is defined.
However, that presumably means that on each re-render, the function is
going to get recreated
You are correct, if you define functions either way, they will get recreated on every re-render. Whether that's a problem or not will depend on your use case.
If you use such a function inside a useEffect callback and add it to its dependency array, the effect will re-run on every re-render (which may not be what you want). If you pass such a function as a prop to any child component(s), that component(s) will also re-render.
You can wrap the functions in question with useCallback, and any child components that receive these as props with React.memo. However, you are now trading the cost of re-rendering components for the cost of storing and comparing props (React will be doing this, not you).
So really, this depends on your app. If the component in question has a large component tree below it, going with useCallback and React.memo might be worth it.

How unperformant are anonymous functions in React component attributes?

You're not supposed to use anonymous functions in react attributes, e.g.
<a onClick=()=>doIt('myId')>Aaron</a>
I understand why this creates a performance problem for React's reconciliation because that anonymous function is recreated on every render pass and will thus always trigger a real DOM re-render of some kind. My question is, for a small component (i.e. not table where every row has a link) is this insignificant? I mean, React is smart enough just to replace the handler, not to re-render the DOM, right? so the cost is not that high?
I feel obliged to inform you that using an Anonymous function and Function.bind(this) in the render triggers a new render. This is because both
doIt.bind(this, 'myId') === doIt.bind(this, 'myId') // false
AND
() => doIt('myId') === () => doIt('myId') // false
are FALSE!
If you want to bind something to a function, use partial application with a method in the React class.
class myComponent extends Component {
doIt = (id) => () => {
// Do Something
}
render() {
<div>
<a onClick={this.doIt('myId')}>Aaron</a>
</div>
}
}
For:
small components: you are ok (almost no performance issues)
large components: the deeper you get the more try to avoid it
In React documentation about event handling, you can find:
In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.
Note: React is not handling callback props differently than other props. It always compares the old and new prop. Thus it re-renders when anonymous function is present because the anonymous function is always newly created.
Your JSX code sample should actually look like this:
<a onClick={ ()=>doIt('myId') }>Aaron</a>
Using an anonymous fat arrow function like this is perfectly valid. You are supposed to use anonymous functions in react attributes. That's okay.
Yes, it's not a best practice. If you want to solve the this context issue when using the ES6 class extends React.Component syntax I would advise you to bind the function in the class constructor.
No, for a 'small' component (i.e. not table where every row has a link) this is not a significant performance issue. You are safe.

React, ineffiencies of binding a new function for each event

My friend and I are having an argument. In the interest of full disclosure, I'm the one who's a big fan of React and its benefits.
In React components, when attaching a DOM event to each element in a list of elements, the traditional pattern is to bind() the generic click handler with the values you want to pass along to that function as parameters. As written below:
<button onClick={this.onButtonClick.bind(this, buttonIndex)}></button>
where buttonIndex is some value that changes as the list of buttons is iterated over. This pattern allows onButtonClick to be generic, and expect buttonIndex as a parameter. Like so:
onButtonClick: function(buttonIndex) {
... some logic
}
My friend argues that this way of doing things is extremely inefficient. This requires that a new function be created and kept in memory to handle each button's event. I agree with his point, but I feel that the React devs wouldn't encourage this pattern in their docs, (at least twice) if the library didn't efficiently handle the events and their handlers.
The pattern he used to avoid this was to use the data- attribute and get the value (in this example, buttonIndex) off the DOM element itself:
<button data-buttonIndex={buttonIndex} onClick={this.onButtonClick}></button>
...
onButtonClick: function() {
var buttonIndex = $(this).data('buttonIndex');
...some logic
}
Again, I'm biased cus I'm the React fan. But this feels wrong, for two reasons:
Getting values off the DOM to pass data around (as state) kinda defeats the purpose of React in a lot of ways, right?
data- attributes are extremely ambiguous in my opinion. They can be set from several different places (HTML, JS, PHP, etc.). And they don't suggest any implicit purpose. That "data" could be used anywhere, (JS, CSS, etc.)
Does React do some special magic to be efficent with its DOM events? And if not, is there an alternative pattern that doesn't use the data- attribute and is more explicit about its use?
I think in general binding functions directly in render is the idiomatic way because they do it in the docs as you pointed out and in our experience has not been significantly less performant. However, there are cases you don't want to rebind the function on every render, for example if you're comparing props in shouldComponentUpdate (like with PureRenderMixin). To do something very similar as your friend suggests but without looking at the DOM with jQuery (and I believe is a common pattern) you can pass the index as a prop.
class Parent extends React.Component {
render() {
return [...some array].map((item, index) => {
return <Child item={item} index={index} />;
});
}
}
class Child extends React.Component {
constructor() {
super();
this.handleClickButton = this.handleClickButton.bind(this);
}
handleClickButton() {
// use this.props.index here
}
render() {
return <button onClick={this.handleClickButton}></button>;
}
}
Note when using ES6 classes you need to bind to this manually in constructor since you're accessing this.props. You don't need to if you're using React.createClass. More about ES6 classes in React docs here.
I'm not sure this is a good idea, but... memoize!
class Foo {
constructor(){
this.getClickHandler = _.memoize(this.getClickHandler);
}
getClickHandler(index){
return (event) => {
doSomething();
};
}
render(){
// ...
<button onClick={this.getClickHandler(index)}>Click me</button>
// ...
}
}
This way you avoid creating a new function, avoid data-attributes, and avoid the performance cost of looking up anything in the dom.
I don't think I've ever profiled and found creating functions in render to be an issue. This is definitely something you should optimize only when the numbers tell you to do so.

Mixins and duplicate methods in React.js

Getting more and more into the awesomeness that is React.js and I've started to use Mixins more.
One thing I noticed, is that both my mixin and my component can have a componentDidMount method — And both functions will be called, so defining it in the component won't override the one in the mixin and vice versa.
Here's an example:
var MyMixin = {
componentDidMount: function() {
// Do something when component is mounted
console.log("Mixin fn ran");
}
};
var Component = React.createClass({
mixins: [MyMixin],
componentDidMount: function() {
// Do something when component is mounted
console.log("Component fn ran");
}
});
Now, the question is wether this is by design or just a coincidence that this works. The lifecycle methods are very useful (To bind and unbind events for instance), so it's not uncommon that both my component and mixins will want to rely on those. The documentation doesn't say anything about this, and I'm wanting to know if I'm setting myself up for a bad time down the road by doing this.
Another question is do I have some kind of control over which method is called first? The one in the mixin or the one in the component.
Yes, it's intentional, and the main factor that makes mixins very powerful in React.
So what happens is:
for the 'component...' functions, they're called in the order of mixin[0], mixins[1], ..., component
propTypes, and the return value of getInitialState and getDefaultProps are merged
other conflicting method names, or conflicts while merging the above results in an error

Categories

Resources