📄 Table of Contents

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ ✦✦✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

How react works

The browser doesn’t understand React. First of all, JSX is converted to JavaScript statements for creating a DOM node i.e., the ReactComponent (stateful) is converted to the ReactElement (stateless + immutable) using ReactDOM.

Now, the ReactElement can be inserted to the virtual DOM, compared and updated fast and easily. How exactly — well, that’s the job of the diff algorithm. The point is — it’s done faster than it would be in the “regular” DOM.

ReactDOM does the work of converting these React Elements to actual DOM nodes and also updates them accordingly.

When React knows the diff — it’s converted to the low-level (HTML DOM) code, which is executed in the DOM. This code is optimised per browser.

import React, { Component, 
PureComponent,
lazy, Suspense,
useState, useEffect
}
from "react";
import ReactDOM from "react-dom";
import {createStore, applyMiddleware} from "redux";
import { Provider, connect } from "react-redux";
Class App extends Component{
constructor(props){
super(props);
this.state= {
count:0
}
}
render(){
return(
<div>
<Count />
</div>
)
}
ReactDOM.render(<App />, document.getElementById("root"));ReactDOM.hydrate(<App />, document.getElementById(‘root')); # 'hydrate' in case of Server-side Rendering

Note that using a constructor is optional, and you can initialise your state like so if your Babel setup has support for class fields:

class MyComponent extends Component {
state = {
counter: 0;
counter: this.props.initialCounterValue,
};
}

This approach is widely preferred. You can also base your state off props.

React Life Cycle version 15.6

this.setState()

Here’s, the dirty secret about setState-it’s actually A-synchronous. React batches state changes for performance reasons, so the state may not change immediately after setState is called.

Here’s the solution — pass a function to setState, with the previous state as an argument.

this.setState(prevState => ({ expanded: !prevState.expanded }), ()=> )

setState() in Asynchronous in nature. It can take a callback function, as well.

Event Handling (recommended method) :

[React Official] : We generally recommend binding in the constructor or using the class fields syntax.

[1]. using the experimental public class fields syntax. This syntax is enabled by default in Create React App.

handleClick = (item) => (e) => {
e.preventDefault();
e.stopPropagation();
};
<MyInput onClick={this.handleClick(item)} />;

[2]. If you aren’t using class fields syntax, you can use an arrow function in the callback:

handleClick(item){
e.preventDefault();
e.stopPropagation();
};
<button onClick={() => this.handleClick()}>//OR<MyInput onClick={(e) => this.handleClick(item, e)}} />;
ComponentWillReceiveProps vs getDerivedStateFromProps

A common misconception is that getDerivedStateFromProps and componentWillReceiveProps are only called when props “change”. These lifecycles are called any time a parent component re-renders, regardless of whether the props are “different” from before.

ComponentWillReceiveProps vs ShouldComponentUpdate

Provider:

import { Provider, connect } from "react-redux";

The <Provider /> makes the Redux’s store available to any nested components that have been wrapped in the connect() function.

Since any React component in a React Redux app can be connected, most applications will render a <Provider> at the top level, with the entire app’s component tree inside of it.

Normally, you can’t use a connected component unless it is nested inside of a <Provider>.

const store=createStore(myReducer, applyMiddleware);<Provider store={store} />

connect()

const mapStateToProps = (state) => {
return {
myName: state.name
}
}
const mapDispatchToProps = (dispatch) => {
return {
changeName:(name)=>{dispatch({type:"CHANGE_NAME", payload: name
})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Counter);

Middleware:

import logger from "redux-logger";
import thunk from "redux-thunk";
import promise from "redux-promise-middleware"
const customMiddleWare = store => next => action => {
console.log("Middleware triggered:", action);
next(action);
}
const store=createStore(myReducer,
applyMiddleware(customMiddleWare, promise, thunk, logger
));
<Provider store={store} />

ContextAPI:

const {Provider, Consumer} = createContext({
locale:{},
logout: () =>{}
}

High Order Component:

High Order Component is actually a function that operates in terms of Components.

const LoaderHOC = (WrappedComponent) => {
return class LoaderHOC extends Component {
render(){
return {
<WrappedComponent {...this.props} />}
}
}
}
export default LoaderHOC

Lazy Loading of Components (≥16.6):

import React, {lazy, Suspense } from "react";
const MyComp = lazy(() => import ('./components/myComp'));
<Suspense fallback = {<div> Loading... </div>}>
<MyComp> </MyComp>
</Suspense>

React Hooks (≥16.8)

React 16.8 introduced a new concept: React hooks are functions that allow you to tap into the React component lifecycle without using the class syntax or directly calling lifecycle methods. Instead of declaring a class, you write a render function.

import React, { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
# const [growth, setGrowth] = useState(0);
# const [nirvana, setNirvana] = useState(false);
# const [message, setMessage] = useState(‘’)

One -way Binding vs Two-way Binding

One way data flow means that the model is the single source of truth. Changes in the UI trigger messages that signal user intent to the model (or “store” in React). Only the model has the access to change the app’s state. The effect is that data always flows in a single direction, which makes it easier to understand.

Two way data binding means that UI fields are bound to model data dynamically such that when a UI field changes, the model data changes with it and vice-versa.

One way data flows are deterministic, whereas two-way binding can cause side-effects which are harder to follow and understand.

Reducers

Why to call super() & pass props to it

There is only one reason when one needs to pass props to super(), when you want to access “this.props” in constructor. Ideally, you are extending the React.Component class, and per the ES2015 spec, a child class constructor cannot make use of this until super() has been called. in simplest terms, ES2015 class constructors have to call super() if they are sub-classes.

React.cloneElement vs this.props.children

props.children isn't the actual children; It is the descriptor of the children. So you don't have actually anything to change; you can't change any props, or edit any functionality; you can only read from it.

But if you need to make any modifications you have to create new elements using React.CloneElement.

https://egghead.io/lessons/react-use-react-cloneelement-to-extend-functionality-of-children-components

An example:

main render function of a component such as App.js:

render() {   
return(
<Paragraph>
<Sentence>First</Sentence>
<Sentence>Second</Sentence>
<Sentence>Third</Sentence>
</Paragraph>
)
}

now let’s say you need to add an onClick to each child of Paragraph; so in your Paragraph.js you can do:

render() {
return (
<div>
{React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
onClick: this.props.onClick })
})}
</div>
)
}

then simply you can do this:

render() {   
return(
<Paragraph onClick={this.onClick}>
<Sentence>First</Sentence>
<Sentence>Second</Sentence>
<Sentence>Third</Sentence>
</Paragraph>
)
}

Note: the React.Children.map function will only see the top level elements, it does not see any of the things that those elements render; meaning that you are providing the direct props to children (here the <Sentence /> elements). If you need the props to be passed down further, let's say you will have a <div></div> inside one of the <Sentence /> elements that wants to use the onClick prop then in that case you can use the Context API to do it. Make the Paragraph the provider and the Sentence elements as consumer.

Render Props:

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function. A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

When Should We Use setState() in React?

First, the basics: Every time we use this.setState(), React re-renders the component.

Let’s divide the whole life of the component into the following categories:

those with GREEN background are the ones where setState() is allowed.

In this phase, the same above order applies here. The only difference between is componentWillReceiveProps() which occurs only there is a change in the props.

Conclusion

As discussed above, please remember NOT to use setState in render, componentWillUpdate and componentDidUpdate which lead to an infinite loop and throw an error.

◉ 9 popular ways to implement css in react

  1. Standard CSS
  2. Inline CSS
  3. CSS Modules
  4. Preprocessors SASS, less, styles, etc
  5. Styled Components
  6. Aphrodite
  7. Radium
  8. JSS
  9. Emotion

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store