All posts by admin

Stateful and stateless components (React)

ref – https://programmingwithmosh.com/javascript/stateful-stateless-components-react/

In a component, state is data we import — typically to show the user — that is subject to change.

Here we have a component Pigeon with a state object that has property pigeons. It is simply an array of pigeons that gets displayed in render. We have state, and we can render things from state.

Also called:

Container vs Presentation components
Smart vs Dumb components.

The literal difference is that one has state, and the other doesn’t.

That means the stateful components are keeping track of changing data, while stateless components print out what is given to them via props, or they always render the same thing.

Stateful/Container/Smart component

Stateless/Presentational/Dumb component

Notice the stateless component is written as a function. As cool as state is, you should always aim to make your components as simple and stateless as possible, so different components can be reused like Lego pieces, even if you don’t have immediate plans to reuse a component. The stateful ones should feel lucky to be so!

Structuring components

Aim to have a parent component keep all the information, and pass it down to its children stateless components.

Doesn’t that look and feel so neat? Having a parent component pass data down to its children also assures that if there is any debugging needed regarding state management, we can go to the parent component to see what’s up, instead of checking state in each child component. All the children components have to worry about is receiving the information as props properly.

So presentational components can vary depending on what information it receives. The difference is that a stateful component keeps track of the information itself, instead of just taking it via props and outputting it.

We can also have components that render static state:

Generally, child components render UI and have no state.

Creating reusable component

Create a stateless reusable component like so:

then use it like so:

React state changes, Virtual DOM, reconciliation

Let’s see what happens under the hood.

At this point, we call setState to tell React that the state of this component will change.

React will then schedule an async call to the render method. Whether its five ms, or ten ms, we don’t know when it happens, but it will happen in the future.

The render function will return a new React element. That element comes from the JSX code.

As each render function produces a new React element, when our state changes, the incoming React element will be different than the previous React element. React will diff them, and then apply the change(s) to the real DOM.

For example:

So when we update the count to 1 in our state object, the data we access in formatCount() within the span tag gets updated.

As we know, each element (button, div, span..etc) is an element in our virtual DOM tree. They get their data from the state object.
And when that state object gets updated as the user plays around with the UI, the current virtual DOM gets scheduled (pushed onto a scheduler) to be rendered asynchronously.

React will diff them and see that the incoming virtual DOM have changed compared to the previous virtual DOM. In our case, our span’s data has been modified.

It will notice that our span is modified because that’s where we have used formatCount() to retrieve the updated count property from the state object.
So it will reach out to the real DOM, and update that span, in order to match what we have in the virtual DOM.

Go to the web page, Inspect Elements, and click on the ‘Increment’ button.
You’ll see that as you push the increment button, it calls

which updates the span. It updates the span because it depending on this.state.count it will update the class name to badge-primary or badge-info, and also update the count integer. Thus, in your Inspect Element, nothing else in the DOM is affected. Only that span element.

How does React render Updates?

Explanation
render() function is the point of entry where the tree of React elements are created. When a state or prop within the component is updated, the render() will return a different tree of React elements. If you use setState() within the component, React immediately detects the state change and re-renders the component.

React then figures out how to efficiently update the UI to match the most recent tree changes.
This is when React updates its virtual DOM first and updates only the object that have changed in the real DOM.

Batch Updates

React follows a batch update mechanism to update the real DOM. Hence, leading to increased performance. This means that updates to the real DOM are sent in batches, instead of sending updates for every single change in state.

The repainting of the UI is the most expensive part, and React efficiently ensures that the real DOM receives only batched updates to repaint the UI.

Explanation

When you use React, at a single point in time you can think of the render() function as creating a tree of React elements. On the next state or props update, that render() function will return a different tree of React elements. React then needs to figure out how to efficiently update the UI to match the most recent tree.

There are some generic solutions to this algorithmic problem of generating the minimum number of operations to transform one tree into another. However, the state of the art algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree.

If we used this in React, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:

– Two elements of different types will produce different trees.
– The developer can hint at which child elements may be stable across different renders with a key prop.

The Diffing Algorithm – reconciliation

When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.

Elements Of Different Types

Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. Going from a tag to img tag or from article tag to Comment tag or from button tag to div tag – any of those will lead to a full rebuild.

When tearing down a tree, old DOM nodes are destroyed. Component instances receive componentWillUnmount(). When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive componentWillMount() and then componentDidMount(). Any state associated with the old tree is lost.

Any components below the root will also get unmounted and have their state destroyed. For example, when diffing:

This will destroy the old Counter and remount a new one.

DOM Elements Of The Same Type

When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes. For example:

By comparing these two elements, React knows to only modify the className on the underlying DOM node.
When updating style, React also knows to update only the properties that changed. For example:

When converting between these two elements, React knows to only modify the color style, not the fontWeight.

Dependency Injection using interfaces in JS

ref – https://github.com/RestlessThinker/Javascript-Interface/blob/master/interface.js

Interfaces in JS are implemented like so:

simply use them whenever you do Constructor dependency injection, or set dependency injection.

Make sure the incoming object implements the functions (duck typing). If it does, then that means the inner objects calls the methods (Inversion of control).

The allows you to easily test the container and the incoming part.

Context (React)

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

Problem

Using context, we can avoid passing props through intermediate elements:

Solution

What is children prop?

Children is a prop this.prop.children that allow you to pass components as data to other components, just like any other prop you use. Component tree put between component’s opening and closing tag will be passed to that component as children prop.

There are a number of methods available in the React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray.

A simple usage of children prop looks like this:

If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context

Component composition

Components use the special children prop to pass children elements directly into their output:

This lets other components pass arbitrary children to them by nesting the JSX:

You can also specify where you want children props to go. In our case, we can position prop children to be placed in certain areas.

We can even specialize it:

Inversion of Control

It might feel redundant to pass down the user and avatarSize props through many levels if in the end only the Avatar component really needs it. It’s also annoying that whenever the Avatar component needs more props from the top, you have to add them at all the intermediate levels too.

One way to solve this issue without context is to pass down the Avatar component itself so that the intermediate components don’t need to know about the user or avatarSize props:

This inversion of control can make your code cleaner in many cases by reducing the amount of props you need to pass through your application and giving more control to the root components. However, this isn’t the right choice in every case: moving more complexity higher in the tree makes those higher-level components more complicated and forces the lower-level components to be more flexible than you may want.

You’re not limited to a single child for a component. You may pass multiple children, or even have multiple separate “slots” for children, as documented here:

Props proxy for HOC components

You can add/edit props passed to the component using props proxy pattern.

In this pattern, we create new props as an object, then use dot operator to deep clone it and pass it into the Wrapped component as additional props.

createElement vs cloneElement

ref – https://stackoverflow.com/questions/35616029/react-createelement-vs-cloneelement

JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI.

Whereas cloneElement is used to clone an element and pass it new props.

Using cloneElement will be usually be faster because you only need to instantiate one initial component.

This jsperf test shows cloneElement to be nearly twice as fast as createElement for Chromium 45 on Linux:

cloneElement ~1.7m ops/second
createElement ~0.85m ops/second

If you have a base component that you can clone without changing, then using cloneElement is a clear choice, both semantically and in terms of performance.

Uncontrolled Components

A Uncontrolled Component is one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

The Uncontrolled Components:
– store its own state
– you query the DOM using a ref to find its current value when you need it.

In the below UserProfile component, the name input is accessed using ref.

Why we must bind prototype functions for event handlers in React?

ref – http://chineseruleof8.com/code/index.php/2020/02/24/this-context/
https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/

First, some basics.

In unrestricted, es5 environment:

when we call a standalone function, the ‘this’ gets dynamically bound to the global object.
when we call a method of a method, the ‘this’ gets dynamically bound to the global object.

If you had an object (or instance) calling the method, you’ll get the ‘this’ gets bound to the object.

However, if you were to use strict mode, ‘this’ inside functions that are standalone, or within a method, would reference undefined

This happens in React because React uses Modules. Modules are strict by default. Thus, ‘this’ in React is null.

Notice how when we have a reference to the prototype function, the calling environment is global. The calling object is actually Global/Window.
Thus, in strict mode, it becomes undefined, rather than displaying the calling instance.

If we don’t use use strict, result would be:

We see that the calling object is Global (or Window in Elements)
This also holds true in function of function.

Simulating event handler executions

Let’s take a look at an example that simulates an event being passed and our handler being executed:

We first execute prototype function display. Hence, the ‘this’ gets dynamically bound to the calling instance. It exists, and then looks for property ‘name’, which it finds. That is why we can successfully log Saurabh.

Now let’s look at the React situation. Initially you get something like this:

Notice that when you click, the ‘this’ is undefined. WHY!?

The reason is that when handlClick is executed by the web environment, it is being executed in a different environment, and a reference somewhere points to our instance’s display function.

Let’s simulate it like this:

Notice foo is not executing handleClick. Rather another reference is executing it. And that reference’s environment here is global.
But wait a minute! Shouldn’t the ‘this’ value point to the global object, since we are running this in non-strict mode according to the rules of default binding, ‘this’ in standalone functions should be pointing to the global object?

This is the not the case because because when we have another reference pointing to
– constructors,
– static functions,
-prototype methods,
they are executed in strict mode. Getter and setter functions are also executed in strict mode.

And when this happens in the global environment, they are returned undefined. This is why handlers in React components will dynamically point this to undefined. The function is running in strict mode, and the executing reference is global.

this is why in React class components, we do this:

that way, when the web environment creates references to react component method and executes, its ‘this’ will point to the class itself.

2020 way of doing this

ref – https://medium.com/front-end-weekly/do-i-still-need-to-bind-react-functions-in-2019-6d0fe72f40d7

Use arrow functions. setText function gets returned whenever onClick is executed.

Use class field syntax for method declaration:

Notice that onClick references a curried function. This means whenever the web environment receives a user click, it will execute

whereas setText’s this is already bound to MyComponent via arrow syntax

Why we can’t use index as key for React list items

ref – http://chineseruleof8.com/code/index.php/2020/06/29/why-we-must-bind-prototype-functions-for-event-handlers-in-react/

source code


create-react-app index-list-example
cd index-list-example
npm start

Go your App.js and change the functional component into a class component.
1) add ‘class App extends React.Component’
2) add constructor
3) add a render prototype function

We then add a state property called list. It’s an array to simply display our list of data.
We put code to map through this list in function render:

Displaying Item data

Now, let’s write a function called Item that will display each item in the list.
As a function component, it takes the prop as a parameter. We use this prop to get each item from the list.
Then display the properties name/id from each item and display it.

then use this Item component in render:

Add items to the list

First, let’s create a button. Remember that standalone functions (due to being referenced in global environment and being run in strict mode), will dynamically
(http://chineseruleof8.com/code/index.php/2020/06/29/why-we-must-bind-prototype-functions-for-event-handlers-in-react/)
set ‘this’ to undefined, we must bind it correctly.

Then in render, we put a button and handler there:

Run it

First, write your name at the top. Then click the button to add items.

When you first write the name ‘ted’, and assigns the index to the key of that component, React will think that ‘ted’ should always appear at index 0.

Thus, as you keep adding items, ted stays at index 0.

However, say we add item to front of the list

Make this code change in prototype function addItem:

Now run it again. We put Mike at the box with timestamp of …940:

However, when we append more items to the front of the list, the name Mike gets displayed erroneously index 0, instead of the correct textfield at …940.

This happens because we erroneously assigned array index to our key. As each Items appear, React will assign different index each time these items are rendered. For example, the first time item1 appears, it gets 0. We append item2 on top, so item2 gets 0, item1 gets 1. See? Their keys have changed. ‘mike’ always gets assigned to key 0, and thus, when item2 appears, it appears in item2, instead of item1.

Solution

The solution to this is to use a unique id as key. Notice when we assigned timestamp to our object’s name, we also assign it to id. Timestamp is unique so every entry will be different. This means every entry’s key will be unique. Thus when they get rendered, their respective data will always be matched to the Component Item’s key. Thus, if we were to put ‘ricky’ at an Item1, no matter what kind of Items get appended at anywhere, React will also look for the Component that has the key with the unique ID to insert ‘ricky’ in.

Full Source