Category: Tutorials

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQyRcKIq3ZLxA9Zg6mrPJbmzdvZksYWe4sHpQ&s

  • Error Boundaries

    In the past, if we get any JavaScript errors inside components, it corrupts the React?s internal state and put React in a broken state on next renders. There are no ways to handle these errors in React components, nor it provides any methods to recover from them. But, React 16 introduces a new concept to handle the errors by using the error boundaries. Now, if any JavaScript error found in a part of the UI, it does not break the whole app.

    Error boundaries are React components which catch JavaScript errors anywhere in our app, log those errors, and display a fallback UI. It does not break the whole app component tree and only renders the fallback UI whenever an error occurred in a component. Error boundaries catch errors during rendering in component lifecycle methods, and constructors of the whole tree below them.Note:

    Sometimes, it is not possible to catch Error boundaries in React application. These are:

    • Event handlers
    • Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
    • Server-side rendering
    • Errors are thrown in the error boundary itself rather than its children.

    For simple React app, we can declare an error boundary once and can use it for the whole application. For a complex application which have multiple components, we can declare multiple error boundaries to recover each part of the entire application.

    We can also report the error to an error monitoring service like Rollbar. This monitoring service provides the ability to track how many users are affected by errors, find causes of them, and improve the user experience.

    Error boundary in class

    A class component can becomes an error boundary if it defines a new lifecycle methods either static getDerivedStateFromError() or componentDidCatch(error, info). We can use static getDerivedStateFromError() to render a fallback UI when an error has been thrown, and can use componentDidCatch() to log error information.

    An error boundary can?t catch the error within itself. If the error boundary fails to render the error message, the error will go to the closest error boundary above it. It is similar to the catch {} block in JavaScript.

    How to implement error boundaries

    Step-1 Create a class which extends React component and passes the props inside it.

    Step-2 Now, add componentDidCatch() method which allows you to catch error in the components below them in the tree.

    Step-3 Next add render() method, which is responsible for how the component should be rendered. For example, it will display the error message like “Something is wrong.”

    Example

    class ErrorBoundary extends React.Component {  
    
      constructor(props) {  
    
        super(props);  
    
        this.state = { hasError: false };  
    
      }  
    
      static getDerivedStateFromError(error) {  
    
        // It will update the state so the next render shows the fallback UI.  
    
        return { hasError: true };  
    
      }  
    
      componentDidCatch(error, info) {  
    
        // It will catch error in any component below. We can also log the error to an error reporting service.  
    
        logErrorToMyService(error, info);  
    
      }  
    
      render() {  
    
        if (this.state.hasError) {  
    
            return (  
    
            <div>Something is wrong.</div>;  
    
        );  
    
        }  
    
        return this.props.children;   
    
      }  
    
    } 

      Step-4 Now, we can use it as a regular component. Add the new component in HTML, which you want to include in the error boundary. In this example, we are adding an error boundary around a MyWidgetCounter component.

      <ErrorBoundary>  
      
             <MyWidgetCounter/>  
      
      </ErrorBoundary> 

        Where to Place Error Boundaries

        An error boundary entirely depends on you. You can use error boundaries on the top-level of the app components or wrap it on the individual components to protect them from breaking the other parts of the app.

        Let us see an example.

        import React from 'react';  
        
        import './App.css'  
        
          
        
        class ErrorBoundary extends React.Component {  
        
          constructor(props) {  
        
            super(props);  
        
            this.state = { error: false, errorInfo: null };  
        
          }  
        
            
        
          componentDidCatch(error, errorInfo) {  
        
            // Catch errors in any components below and re-render with error message  
        
            this.setState({  
        
              error: error,  
        
              errorInfo: errorInfo  
        
            })  
        
          }  
        
            
        
          render() {  
        
            if (this.state.errorInfo) {  
        
              return (  
        
                <div>  
        
                  <h2>Something went wrong.</h2>  
        
                  <details style={{ whiteSpace: 'pre-wrap' }}>  
        
                    {this.state.error && this.state.error.toString()}  
        
                    <br />  
        
                    {this.state.errorInfo.componentStack}  
        
                  </details>  
        
                </div>  
        
              );  
        
            }  
        
            return this.props.children;  
        
          }    
        
        }  
        
          
        
        class BuggyCounter extends React.Component {  
        
          constructor(props) {  
        
            super(props);  
        
            this.state = { counter: 0 };  
        
            this.handleClick = this.handleClick.bind(this);  
        
          }  
        
            
        
          handleClick() {  
        
            this.setState(({counter}) => ({  
        
              counter: counter + 1  
        
            }));  
        
          }  
        
            
        
          render() {  
        
            if (this.state.counter === 3) {  
        
              throw new Error('I crashed!');  
        
            }  
        
            return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;  
        
          }  
        
        }  
        
          
        
        function App() {  
        
          return (  
        
            <div>  
        
              <p><b>Example of Error Boundaries</b></p>  
        
              <hr />  
        
              <ErrorBoundary>  
        
                <p>These two counters are inside the same error boundary.</p>  
        
                  <BuggyCounter />  
        
                  <BuggyCounter />  
        
              </ErrorBoundary>  
        
              <hr />  
        
              <p>These two counters are inside of their individual error boundary.</p>  
        
                <ErrorBoundary><BuggyCounter /></ErrorBoundary>  
        
                <ErrorBoundary><BuggyCounter /></ErrorBoundary>  
        
            </div>  
        
          );  
        
        }  
        
        export default App  

          In the above code snippet, when we click on the numbers, it increases the counters. The counter is programmed to throw an error when it reaches 3. It simulates a JavaScript error in a component. Here, we used an error boundary in two ways, which are given below.

          First, these two counters are inside the same error boundary. If anyone crashes, the error boundary will replace both of them.

          <ErrorBoundary>  
          
                    <BuggyCounter />  
          
                    <BuggyCounter />  
          
          </ErrorBoundary>  

            Second, these two counters are inside of their individual error boundary. So if anyone crashes, the other is not affected.

            <ErrorBoundary><BuggyCounter /></ErrorBoundary>  
            
            <ErrorBoundary><BuggyCounter /></ErrorBoundary>

            Output:

            When we execute the above code, we will get the following output.

            React Error Boundaries

            When the counter has reached at 3, it gives the following output.

            React Error Boundaries

            New Behavior for Uncaught error

            It is an important implication related to error boundaries. If the error does not catch by any error boundary, it will result in unmounting of the whole React application.

            Error Boundary in Event Handler

            Error boundaries do not allow catching errors inside event handlers. React does not need any error boundary to recover from errors in the event handler. If there is a need to catch errors in the event handler, you can use JavaScript try-catch statement.

            In the below example, you can see how an event handler will handle the errors.

            class MyComponent extends React.Component {  
            
              constructor(props) {  
            
                super(props);  
            
                this.state = { error: null };  
            
                this.handleClick = this.handleClick.bind(this);  
            
              }  
            
              
            
              handleClick() {  
            
                try {  
            
                  // Do something which can throw error  
            
                } catch (error) {  
            
                  this.setState({ error });  
            
                }  
            
              }  
            
              
            
              render() {  
            
                if (this.state.error) {  
            
                  return   
            
                      <h2>It caught an error.</h2>  
            
                }  
            
                return <div onClick={this.handleClick}>Click Me</div>  
            
              }  
            
            } 
            1. Portals

              The React 16.0 version introduced React portals in September 2017. A React portal provides a way to render an element outside of its component hierarchy, i.e., in a separate component.

              Before React 16.0 version, it is very tricky to render the child component outside of its parent component hierarchy. If we do this, it breaks the convention where a component needs to render as a new element and follow a parent-child hierarchy. In React, the parent component always wants to go where its child component goes. That’s why React portal concept comes in.

              Syntax

              ReactDOM.createPortal(child, container)  

              Here, the first argument (child) is the component, which can be an element, string, or fragment, and the second argument (container) is a DOM element.

              Example before React v16

              Generally, when you want to return an element from a component’s render method, it is mounted as a new div into the DOM and render the children of the closest parent component.

              render() {  
              
              // React mounts a new div into the DOM and renders the children into it  
              
                return (  
              
                 <div>  
              
                   {this.props.children}  
              
                 </div>  
              
                );  
              
              }  

                Example using portal

                But, sometimes we want to insert a child component into a different location in the DOM. It means React does not want to create a new div. We can do this by creating React portal.

                render() {  
                
                 return ReactDOM.createPortal(  
                
                   this.props.children,  
                
                   myNode,  
                
                 );  
                
                }  

                  Features

                  • It uses React version 16 and its official API for creating portals.
                  • It has a fallback for React version 15.
                  • It transports its children component into a new React portal which is appended by default to document.body.
                  • It can also target user specified DOM element.
                  • It supports server-side rendering
                  • It supports returning arrays (no wrapper div’s needed)
                  • It uses <Portal /> and <PortalWithState /> so there is no compromise between flexibility and convenience.
                  • It doesn’t produce any DOM mess.
                  • It has no dependencies, minimalistic.

                  When to use?

                  The common use-cases of React portal include:

                  • Modals
                  • Tooltips
                  • Floating menus
                  • Widgets

                  Installation

                  We can install React portal using the following command.

                  $ npm install react-portal --save  

                  Explanation of React Portal

                  Create a new React project using the following command.

                  $ npx create-react-app reactapp  

                  Open the App.js file and insert the following code snippet.

                  App.js

                  import React, {Component} from 'react';    
                  
                  import './App.css'  
                  
                  import PortalDemo from './PortalDemo.js';  
                  
                    
                  
                  class App extends Component {    
                  
                      render () {    
                  
                          return (    
                  
                              <div className='App'>  
                  
                           <PortalDemo />  
                  
                      </div>    
                  
                          );    
                  
                      }    
                  
                  }    
                  
                  export default App;

                  The next step is to create a portal component and import it in the App.js file.

                  PortalDemo.js

                  import React from 'react'  
                  
                  import ReactDOM from 'react-dom'  
                  
                    
                  
                  function PortalDemo(){  
                  
                      return ReactDOM.createPortal(  
                  
                        <h1>Portals Demo</h1>,  
                  
                        document.getElementById('portal-root')  
                  
                      )  
                  
                  }  
                  
                  export default PortalDemo  

                    Now, open the Index.html file and add a <div id=”portal-root”></div> element to access the child component outside the root node.

                    Index.html

                    <!DOCTYPE html>  
                    
                    <html lang="en">  
                    
                      <head>  
                    
                        <meta charset="utf-8" />  
                    
                        <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />  
                    
                        <meta name="viewport" content="width=device-width, initial-scale=1" />  
                    
                        <meta name="theme-color" content="#000000" />  
                    
                        <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />  
                    
                        <title>React App</title>  
                    
                      </head>  
                    
                      <body>  
                    
                        <noscript>It is required to enable JavaScript to run this app.</noscript>  
                    
                        <div id="root"></div>  
                    
                        <div id="portal-root"></div>  
                    
                      </body>  
                    
                    </html> 

                      Output:

                      When we execute the React app, we will get the following screen.

                      React Portal

                      Now, open the Inspect (ctrl + shift + I). In this window, select the Elements section and then click on the <div id=”portal-root”></div> component. Here, we can see that each tag is under the “portal-root” DOM node, not the “root” DOM node. Hence, we can see that how React Portal provides the ability to break out of root DOM tree.

                      React Portal
                    1. Redux Example

                      In this section, we will learn how to implements Redux in React application. Here, we provide a simple example to connect Redux and React.

                      Step-1 Create a new react project using create-react-app command. I choose the project name: “reactproject.” Now, install Redux and React-Redux.

                      javatpoint@root:~/Desktop$ npx create-react-app reactproject  
                      
                      javatpoint@root:~/Desktop/reactproject$ npm install redux react-redux --save 

                        Step-2 Create Files and Folders

                        In this step, we need to create folders and files for actions, reducers, components, and containers. After creating folders and files, our project looks like as below image.

                        React Redux Example

                        Step-3 Actions

                        It uses ‘type‘ property to inform about data that should be sent to the Store. In this folder, we will create two files: index.js and index.spec.js. Here, we have created an action creator that returns our action and sets an id for every created item.

                        Index.js

                        let nextTodoId = 0  
                        
                        export const addTodo = text => ({  
                        
                          type: 'ADD_TODO',  
                        
                          id: nextTodoId++,  
                        
                          text  
                        
                        })  
                        
                          
                        
                        export const setVisibilityFilter = filter => ({  
                        
                          type: 'SET_VISIBILITY_FILTER',  
                        
                          filter  
                        
                        })  
                        
                          
                        
                        export const toggleTodo = id => ({  
                        
                          type: 'TOGGLE_TODO',  
                        
                          id  
                        
                        })  
                        
                          
                        
                        export const VisibilityFilters = {  
                        
                          SHOW_ALL: 'SHOW_ALL',  
                        
                          SHOW_COMPLETED: 'SHOW_COMPLETED',  
                        
                          SHOW_ACTIVE: 'SHOW_ACTIVE'  
                        
                        } 

                          Index.spec.js

                          import * as actions from './index'  
                          
                            
                          
                          describe('todo actions', () => {  
                          
                            it('addTodo should create ADD_TODO action', () => {  
                          
                              expect(actions.addTodo('Use Redux')).toEqual({  
                          
                                type: 'ADD_TODO',  
                          
                                id: 0,  
                          
                                text: 'Use Redux'  
                          
                              })  
                          
                            })  
                          
                            
                          
                            it('setVisibilityFilter should create SET_VISIBILITY_FILTER action', () => {  
                          
                              expect(actions.setVisibilityFilter('active')).toEqual({  
                          
                                type: 'SET_VISIBILITY_FILTER',  
                          
                                filter: 'active'  
                          
                              })  
                          
                            })  
                          
                            
                          
                            it('toggleTodo should create TOGGLE_TODO action', () => {  
                          
                              expect(actions.toggleTodo(1)).toEqual({  
                          
                                type: 'TOGGLE_TODO',  
                          
                                id: 1  
                          
                              })  
                          
                            })  
                          
                          })

                          Step-4 Reducers

                          As we know, Actions only trigger changes in the app, and the Reducers specify those changes. The Reducer is a function which takes two parameters ‘Action’ and ‘State’ to calculate and return an updated State. It read the payloads from the ‘Actions’ and then updates the ‘Store’ via the State accordingly.

                          In the given files, each Reducer managing its own part of the global State. The State parameter is different for every Reducer and corresponds to the part of the ‘State’ it manages. When the app becomes larger, we can split the Reducers into separate files and keep them completely independent and managing different data domains.

                          Here, we are using ‘combineReducers’ helper function to add any new Reducers we might use in the future.

                          index.js

                          import { combineReducers } from 'redux'  
                          
                          import todos from './todos'  
                          
                          import visibilityFilter from './visibilityFilter'  
                          
                            
                          
                          export default combineReducers({  
                          
                            todos,  
                          
                            visibilityFilter  
                          
                          }) 

                            Todos.js

                            const todos = (state = [], action) => {  
                            
                              switch (action.type) {  
                            
                                case 'ADD_TODO':  
                            
                                  return [  
                            
                                    ...state,  
                            
                                    {  
                            
                                      id: action.id,  
                            
                                      text: action.text,  
                            
                                      completed: false  
                            
                                    }  
                            
                                  ]  
                            
                                case 'TOGGLE_TODO':  
                            
                                  return state.map(todo =>  
                            
                                    (todo.id === action.id)  
                            
                                      ? {...todo, completed: !todo.completed}  
                            
                                      : todo  
                            
                                  )  
                            
                                default:  
                            
                                  return state  
                            
                              }  
                            
                            }  
                            
                            export default todos 

                              Todos.spec.js

                              import todos from './todos'  
                              
                                
                              
                              describe('todos reducer', () => {  
                              
                                it('should handle initial state', () => {  
                              
                                  expect(  
                              
                                    todos(undefined, {})  
                              
                                  ).toEqual([])  
                              
                                })  
                              
                                
                              
                                it('should handle ADD_TODO', () => {  
                              
                                  expect(  
                              
                                    todos([], {  
                              
                                      type: 'ADD_TODO',  
                              
                                      text: 'Run the tests',  
                              
                                      id: 0  
                              
                                    })  
                              
                                  ).toEqual([  
                              
                                    {  
                              
                                      text: 'Run the tests',  
                              
                                      completed: false,  
                              
                                      id: 0  
                              
                                    }  
                              
                                  ])  
                              
                                
                              
                                  expect(  
                              
                                    todos([  
                              
                                      {  
                              
                                        text: 'Run the tests',  
                              
                                        completed: false,  
                              
                                        id: 0  
                              
                                      }  
                              
                                    ], {  
                              
                                      type: 'ADD_TODO',  
                              
                                      text: 'Use Redux',  
                              
                                      id: 1  
                              
                                    })  
                              
                                  ).toEqual([  
                              
                                    {  
                              
                                      text: 'Run the tests',  
                              
                                      completed: false,  
                              
                                      id: 0  
                              
                                    }, {  
                              
                                      text: 'Use Redux',  
                              
                                      completed: false,  
                              
                                      id: 1  
                              
                                    }  
                              
                                  ])  
                              
                                
                              
                                  expect(  
                              
                                    todos([  
                              
                                      {  
                              
                                        text: 'Run the tests',  
                              
                                        completed: false,  
                              
                                        id: 0  
                              
                                      }, {  
                              
                                        text: 'Use Redux',  
                              
                                        completed: false,  
                              
                                        id: 1  
                              
                                      }  
                              
                                    ], {  
                              
                                      type: 'ADD_TODO',  
                              
                                      text: 'Fix the tests',  
                              
                                      id: 2  
                              
                                    })  
                              
                                  ).toEqual([  
                              
                                    {  
                              
                                      text: 'Run the tests',  
                              
                                      completed: false,  
                              
                                      id: 0  
                              
                                    }, {  
                              
                                      text: 'Use Redux',  
                              
                                      completed: false,  
                              
                                      id: 1  
                              
                                    }, {  
                              
                                      text: 'Fix the tests',  
                              
                                      completed: false,  
                              
                                      id: 2  
                              
                                    }  
                              
                                  ])  
                              
                                })  
                              
                                
                              
                                it('should handle TOGGLE_TODO', () => {  
                              
                                  expect(  
                              
                                    todos([  
                              
                                      {  
                              
                                        text: 'Run the tests',  
                              
                                        completed: false,  
                              
                                        id: 1  
                              
                                      }, {  
                              
                                        text: 'Use Redux',  
                              
                                        completed: false,  
                              
                                        id: 0  
                              
                                      }  
                              
                                    ], {  
                              
                                      type: 'TOGGLE_TODO',  
                              
                                      id: 1  
                              
                                    })  
                              
                                  ).toEqual([  
                              
                                    {  
                              
                                      text: 'Run the tests',  
                              
                                      completed: true,  
                              
                                      id: 1  
                              
                                    }, {  
                              
                                      text: 'Use Redux',  
                              
                                      completed: false,  
                              
                                      id: 0  
                              
                                    }  
                              
                                  ])  
                              
                                })  
                              
                              })  

                                VisibilityFilter.js

                                import { VisibilityFilters } from '../actions'  
                                
                                  
                                
                                const visibilityFilter = (state = VisibilityFilters.SHOW_ALL, action) => {  
                                
                                  switch (action.type) {  
                                
                                    case 'SET_VISIBILITY_FILTER':  
                                
                                      return action.filter  
                                
                                    default:  
                                
                                      return state  
                                
                                  }  
                                
                                }  
                                
                                export default visibilityFilter  

                                  Step-5 Components

                                  It is a Presentational Component, which concerned with how things look such as markup, styles. It receives data and invokes callbacks exclusively via props. It does not know where the data comes from or how to change it. It only renders what is given to them.

                                  App.js

                                  It is the root component which renders everything in the UI.

                                  import React from 'react'  
                                  
                                  import Footer from './Footer'  
                                  
                                  import AddTodo from '../containers/AddTodo'  
                                  
                                  import VisibleTodoList from '../containers/VisibleTodoList'  
                                  
                                    
                                  
                                  const App = () => (  
                                  
                                    <div>  
                                  
                                      <AddTodo />  
                                  
                                      <VisibleTodoList />  
                                  
                                      <Footer />  
                                  
                                    </div>  
                                  
                                  )  
                                  
                                  export default App 

                                    Footer.js

                                    It tells where the user changes currently visible todos.

                                    import React from 'react'  
                                    
                                    import FilterLink from '../containers/FilterLink'  
                                    
                                    import { VisibilityFilters } from '../actions'  
                                    
                                      
                                    
                                    const Footer = () => (  
                                    
                                      <p>  
                                    
                                        Show: <FilterLink filter={VisibilityFilters.SHOW_ALL}>All</FilterLink>  
                                    
                                        {', '}  
                                    
                                        <FilterLink filter={VisibilityFilters.SHOW_ACTIVE}>Active</FilterLink>  
                                    
                                        {', '}  
                                    
                                        <FilterLink filter={VisibilityFilters.SHOW_COMPLETED}>Completed</FilterLink>  
                                    
                                      </p>  
                                    
                                    )  
                                    
                                    export default Footer  

                                      Link.js

                                      It is a link with a callback.

                                        import React from 'react'  
                                      
                                      import PropTypes from 'prop-types'  
                                      
                                        
                                      
                                      const Link = ({ active, children, onClick }) => {  
                                      
                                        if (active) {  
                                      
                                          return <span>{children}</span>  
                                      
                                        }  
                                      
                                        
                                      
                                        return (  
                                      
                                          <a  
                                      
                                            href=""  
                                      
                                            onClick={e => {  
                                      
                                              e.preventDefault()  
                                      
                                              onClick()  
                                      
                                            }}  
                                      
                                          >  
                                      
                                            {children}  
                                      
                                          </a>  
                                      
                                        )  
                                      
                                      }  
                                      
                                        
                                      
                                      Link.propTypes = {  
                                      
                                        active: PropTypes.bool.isRequired,  
                                      
                                        children: PropTypes.node.isRequired,  
                                      
                                        onClick: PropTypes.func.isRequired  
                                      
                                      }  
                                      
                                        
                                      
                                      export default Link

                                        Todo.js

                                        It represents a single todo item which shows text.

                                        import React from 'react'  
                                        
                                        import PropTypes from 'prop-types'  
                                        
                                          
                                        
                                        const Todo = ({ onClick, completed, text }) => (  
                                        
                                          <li  
                                        
                                            onClick={onClick}  
                                        
                                            style={{  
                                        
                                              textDecoration: completed ? 'line-through' : 'none'  
                                        
                                            }}  
                                        
                                          >  
                                        
                                            {text}  
                                        
                                          </li>  
                                        
                                        )  
                                        
                                          
                                        
                                        Todo.propTypes = {  
                                        
                                          onClick: PropTypes.func.isRequired,  
                                        
                                          completed: PropTypes.bool.isRequired,  
                                        
                                          text: PropTypes.string.isRequired  
                                        
                                        }  
                                        
                                          
                                        
                                        export default Todo  

                                          TodoList.js

                                          It is a list to show visible todos{ id, text, completed }.

                                          import React from 'react'  
                                          
                                          import PropTypes from 'prop-types'  
                                          
                                          import Todo from './Todo'  
                                          
                                            
                                          
                                          const TodoList = ({ todos, onTodoClick }) => (  
                                          
                                            <ul>  
                                          
                                              {todos.map((todo, index) => (  
                                          
                                                <Todo key={index} {...todo} onClick={() => onTodoClick(index)} />  
                                          
                                              ))}  
                                          
                                            </ul>  
                                          
                                          )  
                                          
                                            
                                          
                                          TodoList.propTypes = {  
                                          
                                            todos: PropTypes.arrayOf(  
                                          
                                              PropTypes.shape({  
                                          
                                                id: PropTypes.number.isRequired,  
                                          
                                                completed: PropTypes.bool.isRequired,  
                                          
                                                text: PropTypes.string.isRequired  
                                          
                                              }).isRequired  
                                          
                                            ).isRequired,  
                                          
                                            onTodoClick: PropTypes.func.isRequired  
                                          
                                          }  
                                          
                                          export default TodoList

                                            Step-6 Containers

                                            It is a Container Component which concerned with how things work such as data fetching, updates State. It provides data and behavior to presentational components or other container components. It uses Redux State to read data and dispatch Redux Action for updating data.

                                            AddTodo.js

                                            It contains the input field with an ADD (submit) button.

                                            import React from 'react'  
                                            
                                            import { connect } from 'react-redux'  
                                            
                                            import { addTodo } from '../actions'  
                                            
                                              
                                            
                                            const AddTodo = ({ dispatch }) => {  
                                            
                                              let input  
                                            
                                              
                                            
                                              return (  
                                            
                                                <div>  
                                            
                                                  <form onSubmit={e => {  
                                            
                                                    e.preventDefault()  
                                            
                                                    if (!input.value.trim()) {  
                                            
                                                      return  
                                            
                                                    }  
                                            
                                                    dispatch(addTodo(input.value))  
                                            
                                                    input.value = ''  
                                            
                                                  }}>  
                                            
                                                    <input ref={node => input = node} />  
                                            
                                                    <button type="submit">  
                                            
                                                      Add Todo  
                                            
                                                    </button>  
                                            
                                                  </form>  
                                            
                                                </div>  
                                            
                                              )  
                                            
                                            }  
                                            
                                            export default connect()(AddTodo)  

                                              FilterLink.js

                                              It represents the current visibility filter and renders a link.

                                              import { connect } from 'react-redux'  
                                              
                                              import { setVisibilityFilter } from '../actions'  
                                              
                                              import Link from '../components/Link'  
                                              
                                                
                                              
                                              const mapStateToProps = (state, ownProps) => ({  
                                              
                                                active: ownProps.filter === state.visibilityFilter  
                                              
                                              })  
                                              
                                                
                                              
                                              const mapDispatchToProps = (dispatch, ownProps) => ({  
                                              
                                                onClick: () => dispatch(setVisibilityFilter(ownProps.filter))  
                                              
                                              })  
                                              
                                                
                                              
                                              export default connect(  
                                              
                                                mapStateToProps,  
                                              
                                                mapDispatchToProps  
                                              
                                              )(Link)  

                                                VisibleTodoList.js

                                                It filters the todos and renders a TodoList.

                                                import { connect } from 'react-redux'  
                                                
                                                import { toggleTodo } from '../actions'  
                                                
                                                import TodoList from '../components/TodoList'  
                                                
                                                import { VisibilityFilters } from '../actions'  
                                                
                                                  
                                                
                                                const getVisibleTodos = (todos, filter) => {  
                                                
                                                  switch (filter) {  
                                                
                                                    case VisibilityFilters.SHOW_ALL:  
                                                
                                                      return todos  
                                                
                                                    case VisibilityFilters.SHOW_COMPLETED:  
                                                
                                                      return todos.filter(t => t.completed)  
                                                
                                                    case VisibilityFilters.SHOW_ACTIVE:  
                                                
                                                      return todos.filter(t => !t.completed)  
                                                
                                                    default:  
                                                
                                                      throw new Error('Unknown filter: ' + filter)  
                                                
                                                  }  
                                                
                                                }  
                                                
                                                  
                                                
                                                const mapStateToProps = state => ({  
                                                
                                                  todos: getVisibleTodos(state.todos, state.visibilityFilter)  
                                                
                                                })  
                                                
                                                  
                                                
                                                const mapDispatchToProps = dispatch => ({  
                                                
                                                  toggleTodo: id => dispatch(toggleTodo(id))  
                                                
                                                })  
                                                
                                                  
                                                
                                                export default connect(  
                                                
                                                  mapStateToProps,  
                                                
                                                  mapDispatchToProps  
                                                
                                                )(TodoList) 

                                                  Step-7 Store

                                                  All container components need access to the Redux Store to subscribe to it. For this, we need to pass it(store) as a prop to every container component. However, it gets tedious. So we recommend using special React Redux component calledwhich make the store available to all container components without passing it explicitly. It used once when you render the root component.

                                                  index.js

                                                  import React from 'react'  
                                                  
                                                  import { render } from 'react-dom'  
                                                  
                                                  import { createStore } from 'redux'  
                                                  
                                                  import { Provider } from 'react-redux'  
                                                  
                                                  import App from './components/App'  
                                                  
                                                  import rootReducer from './reducers'  
                                                  
                                                    
                                                  
                                                  const store = createStore(rootReducer)  
                                                  
                                                    
                                                  
                                                  render(  
                                                  
                                                    <Provider store={store}>  
                                                  
                                                      <App />  
                                                  
                                                    </Provider>,  
                                                  
                                                    document.getElementById('root')  
                                                  
                                                  )  

                                                    Output

                                                    When we execute the application, it gives the output as below screen.

                                                    React Redux Example

                                                    Now, we will be able to add items in the list.

                                                    React Redux Example

                                                    The detailed explanation of React-Redux example can be shown here: https://redux.js.org/basics/usage-with-react.

                                                  1. Redux

                                                    Redux is an open-source JavaScript library used to manage application state. React uses Redux for building the user interface. It was first introduced by Dan Abramov and Andrew Clark in 2015.

                                                    React Redux is the official React binding for Redux. It allows React components to read data from a Redux Store, and dispatch Actions to the Store to update data. Redux helps apps to scale by providing a sensible way to manage state through a unidirectional data flow model. React Redux is conceptually simple. It subscribes to the Redux store, checks to see if the data which your component wants have changed, and re-renders your component.

                                                    Redux was inspired by Flux. Redux studied the Flux architecture and omitted unnecessary complexity.

                                                    • Redux does not have Dispatcher concept.
                                                    • Redux has an only Store whereas Flux has many Stores.
                                                    • The Action objects will be received and handled directly by Store.

                                                    Why use React Redux?

                                                    The main reason to use React Redux are:

                                                    • React Redux is the official UI bindings for react Application. It is kept up-to-date with any API changes to ensure that your React components behave as expected.
                                                    • It encourages good ‘React’ architecture.
                                                    • It implements many performance optimizations internally, which allows to components re-render only when it actually needs.

                                                    Redux Architecture

                                                    React Redux

                                                    The components of Redux architecture are explained below.

                                                    STORE: A Store is a place where the entire state of your application lists. It manages the status of the application and has a dispatch(action) function. It is like a brain responsible for all moving parts in Redux.

                                                    ACTION: Action is sent or dispatched from the view which are payloads that can be read by Reducers. It is a pure object created to store the information of the user’s event. It includes information such as type of action, time of occurrence, location of occurrence, its coordinates, and which state it aims to change.

                                                    REDUCER: Reducer read the payloads from the actions and then updates the store via the state accordingly. It is a pure function to return a new state from the initial state.

                                                    Redux Installation

                                                    Requirements: React Redux requires React 16.8.3 or later version.

                                                    To use React Redux with React application, you need to install the below command.

                                                    $ npm install redux react-redux --save  
                                                    React Redux
                                                  2. Flux Vs. MVC

                                                    MVC

                                                    MVC stands for Model View Controller. It is an architectural pattern used for developing the user interface. It divides the application into three different logical components: the Model, the View, and the Controller. It is first introduced in 1976 in the Smalltalk programming language. In MVC, each component is built to handle specific development aspect of an application. It is one of the most used web development frameworks to create scalable projects.

                                                    MVC Architecture

                                                    The MVC architecture contains the three components. These are:

                                                    • Model: It is responsible for maintaining the behavior and data of an application.
                                                    • View: It is used to display the model in the user interface.
                                                    • Controller: It acts as an interface between the Model and the View components. It takes user input, manipulates the data(model) and causes the view to update.
                                                    React Flux Vs. MVC

                                                    Flux

                                                    According to the official site, Flux is the application architecture that Facebook uses for building client-side web applications. It is an alternative to MVC architecture and other software design patterns for managing how data flows in the react application. It is the backbone of all React application. It is not a library nor a framework. It complements React as view and follows the concept of Unidirectional Data Flow model.

                                                    Flux Architecture has three major roles in dealing with data:

                                                    1. Dispatcher
                                                    2. Stores
                                                    3. Views (React components)
                                                    React Flux Vs. MVC

                                                    MVC Vs. Flux

                                                    SNMVCFLUX
                                                    1.It was introduced in 1976.It was introduced just a few years ago.
                                                    2.It supports Bi-directional data Flow model.It supports Uni-directional data flow model.
                                                    3.In this, data binding is the key.In this, events or actions are the keys.
                                                    4.It is synchronous.It is asynchronous.
                                                    5.Here, controllers handle everything(logic).Here, stores handle all logic.
                                                    6.It is hard to debug.It is easy to debug because it has common initiating point: Dispatcher.
                                                    7.It is difficult to understand as the project size increases.It is easy to understand.
                                                    8.Its maintainability is difficult as the project scope goes huge.Its maintainability is easy and reduces runtime errors.
                                                    9.Testing of application is difficult.Testing of application is easy.
                                                    10.Scalability is complex.It can be easily scalable.
                                                  3. Flux Concept

                                                    Flux is an application architecture that Facebook uses internally for building the client-side web application with React. It is not a library nor a framework. It is neither a library nor a framework. It is a kind of architecture that complements React as view and follows the concept of Unidirectional Data Flow model. It is useful when the project has dynamic data, and we need to keep the data updated in an effective manner. It reduces the runtime errors.

                                                    Flux applications have three major roles in dealing with data:

                                                    1. Dispatcher
                                                    2. Stores
                                                    3. Views (React components)

                                                    Here, you should not be confused with the Model-View-Controller (MVC) model. Although, Controllers exists in both, but Flux controller-views (views) found at the top of the hierarchy. It retrieves data from the stores and then passes this data down to their children. Additionally, action creators – dispatcher helper methods used to describe all changes that are possible in the application. It can be useful as a fourth part of the Flux update cycle.

                                                    Structure and Data Flow

                                                    React Flux Concept

                                                    In Flux application, data flows in a single direction(unidirectional). This data flow is central to the flux pattern. The dispatcher, stores, and views are independent nodes with inputs and outputs. The actions are simple objects that contain new data and type property. Now, let us look at the various components of flux architecture one by one.

                                                    Dispatcher

                                                    It is a central hub for the React Flux application and manages all data flow of your Flux application. It is a registry of callbacks into the stores. It has no real intelligence of its own, and simply acts as a mechanism for distributing the actions to the stores. All stores register itself and provide a callback. It is a place which handled all events that modify the store. When an action creator provides a new action to the dispatcher, all stores receive that action via the callbacks in the registry.

                                                    The dispatcher’s API has five methods. These are:

                                                    SNMethodsDescriptions
                                                    1.register()It is used to register a store’s action handler callback.
                                                    2.unregister()It is used to unregisters a store’s callback.
                                                    3.waitFor()It is used to wait for the specified callback to run first.
                                                    4.dispatch()It is used to dispatches an action.
                                                    5.isDispatching()It is used to checks if the dispatcher is currently dispatching an action.

                                                    Stores

                                                    It primarily contains the application state and logic. It is similar to the model in a traditional MVC. It is used for maintaining a particular state within the application, updates themselves in response to an action, and emit the change event to alert the controller view.

                                                    Views

                                                    It is also called as controller-views. It is located at the top of the chain to store the logic to generate actions and receive new data from the store. It is a React component listen to change events and receives the data from the stores and re-render the application.

                                                    Actions

                                                    The dispatcher method allows us to trigger a dispatch to the store and include a payload of data, which we call an action. It is an action creator or helper methods that pass the data to the dispatcher.

                                                    Advantage of Flux

                                                    • It is a unidirectional data flow model which is easy to understand.
                                                    • It is open source and more of a design pattern than a formal framework like MVC architecture.
                                                    • The flux application is easier to maintain.
                                                    • The flux application parts are decoupled.
                                                  4. Hooks

                                                    Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which “hook into” React state and lifecycle features from function components. It does not work inside classes.

                                                    Hooks are backward-compatible, which means it does not contain any breaking changes. Also, it does not replace your knowledge of React concepts.

                                                    When to use a Hooks

                                                    If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing function component.

                                                    Rules of Hooks

                                                    Hooks are similar to JavaScript functions, but you need to follow these two rules when using them. Hooks rule ensures that all the stateful logic in a component is visible in its source code. These rules are:

                                                    1. Only call Hooks at the top level

                                                    Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at the top level of the React functions. This rule ensures that Hooks are called in the same order each time a components renders.

                                                    2. Only call Hooks from React functions

                                                    You cannot call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Hooks can also be called from custom Hooks.

                                                    Pre-requisites for React Hooks

                                                    1. Node version 6 or above
                                                    2. NPM version 5.2 or above
                                                    3. Create-react-app tool for running the React App

                                                    React Hooks Installation

                                                    To use React Hooks, we need to run the following commands:

                                                    $ npm install [email protected] --save  
                                                    
                                                    $ npm install [email protected] --save  

                                                      The above command will install the latest React and React-DOM alpha versions which support React Hooks. Make sure the package.json file lists the React and React-DOM dependencies as given below.

                                                      "react": "^16.8.0-alpha.1",  
                                                      
                                                      "react-dom": "^16.8.0-alpha.1",

                                                      Hooks State

                                                      Hook state is the new way of declaring a state in React app. Hook uses useState() functional component for setting and retrieving state. Let us understand Hook state with the following example.

                                                      App.js

                                                      import React, { useState } from 'react';  
                                                      
                                                        
                                                      
                                                      function CountApp() {  
                                                      
                                                        // Declare a new state variable, which we'll call "count"  
                                                      
                                                        const [count, setCount] = useState(0);  
                                                      
                                                        
                                                      
                                                        return (  
                                                      
                                                          <div>  
                                                      
                                                            <p>You clicked {count} times</p>  
                                                      
                                                            <button onClick={() => setCount(count + 1)}>  
                                                      
                                                              Click me  
                                                      
                                                            </button>  
                                                      
                                                          </div>  
                                                      
                                                        );  
                                                      
                                                      }  
                                                      
                                                      export default CountApp; 

                                                        output:

                                                        React Hooks

                                                        In the above example, useState is the Hook which needs to call inside a function component to add some local state to it. The useState returns a pair where the first element is the current state value/initial value, and the second one is a function which allows us to update it. After that, we will call this function from an event handler or somewhere else. The useState is similar to this.setState in class. The equivalent code without Hooks looks like as below.

                                                        App.js

                                                        import React, { useState } from 'react';  
                                                        
                                                          
                                                        
                                                        class CountApp extends React.Component {  
                                                        
                                                          constructor(props) {  
                                                        
                                                            super(props);  
                                                        
                                                            this.state = {  
                                                        
                                                              count: 0  
                                                        
                                                            };  
                                                        
                                                          }  
                                                        
                                                          render() {  
                                                        
                                                            return (  
                                                        
                                                              <div>  
                                                        
                                                                <p><b>You clicked {this.state.count} times</b></p>  
                                                        
                                                                <button onClick={() => this.setState({ count: this.state.count + 1 })}>  
                                                        
                                                                  Click me  
                                                        
                                                                </button>  
                                                        
                                                              </div>  
                                                        
                                                            );  
                                                        
                                                          }  
                                                        
                                                        }  
                                                        
                                                        export default CountApp;  

                                                          Hooks Effect

                                                          The Effect Hook allows us to perform side effects (an action) in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.

                                                          Side effects have common features which the most web applications need to perform, such as:

                                                          • Updating the DOM,
                                                          • Fetching and consuming data from a server API,
                                                          • Setting up a subscription, etc.

                                                          Let us understand Hook Effect with the following example.

                                                          import React, { useState, useEffect } from 'react';  
                                                          
                                                            
                                                          
                                                          function CounterExample() {  
                                                          
                                                            const [count, setCount] = useState(0);  
                                                          
                                                            
                                                          
                                                            // Similar to componentDidMount and componentDidUpdate:  
                                                          
                                                            useEffect(() => {  
                                                          
                                                              // Update the document title using the browser API  
                                                          
                                                              document.title = You clicked ${count} times;  
                                                          
                                                            });  
                                                          
                                                            
                                                          
                                                            return (  
                                                          
                                                              <div>  
                                                          
                                                                <p>You clicked {count} times</p>  
                                                          
                                                                <button onClick={() => setCount(count + 1)}>  
                                                          
                                                                  Click me  
                                                          
                                                                </button>  
                                                          
                                                              </div>  
                                                          
                                                            );  
                                                          
                                                          }  
                                                          
                                                          export default CounterExample;  

                                                            The above code is based on the previous example with a new feature which we set the document title to a custom message, including the number of clicks.

                                                            Output:

                                                            React Hooks

                                                            In React component, there are two types of side effects:

                                                            1. Effects Without Cleanup
                                                            2. Effects With Cleanup

                                                            Effects without Cleanup

                                                            It is used in useEffect which does not block the browser from updating the screen. It makes the app more responsive. The most common example of effects which don’t require a cleanup are manual DOM mutations, Network requests, Logging, etc.

                                                            Effects with Cleanup

                                                            Some effects require cleanup after DOM updation. For example, if we want to set up a subscription to some external data source, it is important to clean up memory so that we don’t introduce a memory leak. React performs the cleanup of memory when the component unmounts. However, as we know that, effects run for every render method and not just once. Therefore, React also cleans up effects from the previous render before running the effects next time.

                                                            Custom Hooks

                                                            A custom Hook is a JavaScript function. The name of custom Hook starts with “use” which can call other Hooks. A custom Hook is just like a regular function, and the word “use” in the beginning tells that this function follows the rules of Hooks. Building custom Hooks allows you to extract component logic into reusable functions.

                                                            Let us understand how custom Hooks works in the following example.

                                                            import React, { useState, useEffect } from 'react';  
                                                            
                                                              
                                                            
                                                            const useDocumentTitle = title => {  
                                                            
                                                              useEffect(() => {  
                                                            
                                                                document.title = title;  
                                                            
                                                              }, [title])  
                                                            
                                                            }  
                                                            
                                                              
                                                            
                                                            function CustomCounter() {  
                                                            
                                                              const [count, setCount] = useState(0);  
                                                            
                                                              const incrementCount = () => setCount(count + 1);  
                                                            
                                                              useDocumentTitle(You clicked ${count} times);  
                                                            
                                                              // useEffect(() => {  
                                                            
                                                              //   document.title = You clicked ${count} times  
                                                            
                                                              // });  
                                                            
                                                              
                                                            
                                                              return (  
                                                            
                                                                <div>  
                                                            
                                                                  <p>You clicked {count} times</p>  
                                                            
                                                                  <button onClick={incrementCount}>Click me</button>  
                                                            
                                                                </div>  
                                                            
                                                              )  
                                                            
                                                            }  
                                                            
                                                            export default CustomCounter; 

                                                              In the above snippet, useDocumentTitle is a custom Hook which takes an argument as a string of text which is a title. Inside this Hook, we call useEffect Hook and set the title as long as the title has changed. The second argument will perform that check and update the title only when its local state is different than what we are passing in.

                                                              Note: A custom Hook is a convention which naturally follows from the design of Hooks, instead of a React feature.

                                                              Built-in Hooks

                                                              Here, we describe the APIs for the built-in Hooks in React. The built-in Hooks can be divided into two parts, which are given below.

                                                              Basic Hooks

                                                              • useState
                                                              • useEffect
                                                              • useContext

                                                              Additional Hooks

                                                              • useReducer
                                                              • useCallback
                                                              • useMemo
                                                              • useRef
                                                              • useImperativeHandle
                                                              • useLayoutEffect
                                                              • useDebugValue
                                                            1. Context

                                                              Context allows passing data through the component tree without passing props down manually at every level.

                                                              In React application, we passed data in a top-down approach via props. Sometimes it is inconvenient for certain types of props that are required by many components in the React application. Context provides a way to pass values between components without explicitly passing a prop through every level of the component tree.

                                                              How to use Context

                                                              There are two main steps to use the React context into the React application:

                                                              1. Setup a context provider and define the data which you want to store.
                                                              2. Use a context consumer whenever you need the data from the store

                                                              When to use Context

                                                              Context is used to share data which can be considered “global” for React components tree and use that data where needed, such as the current authenticated user, theme, etc. For example, in the below code snippet, we manually thread through a “theme” prop to style the Button component.

                                                              class App extends React.Component {  
                                                              
                                                                render() {  
                                                              
                                                                  return <Toolbar theme="dark" />;  
                                                              
                                                                }  
                                                              
                                                              }  
                                                              
                                                                
                                                              
                                                              function Toolbar(props) {  
                                                              
                                                                return (  
                                                              
                                                                  <div>  
                                                              
                                                                    <ThemedButton theme={props.theme} />  
                                                              
                                                                  </div>  
                                                              
                                                                );  
                                                              
                                                              }  
                                                              
                                                                
                                                              
                                                              class ThemedButton extends React.Component {  
                                                              
                                                                render() {  
                                                              
                                                                  return <Button theme={this.props.theme} />;  
                                                              
                                                                }  
                                                              
                                                              } 

                                                                In the above code, the Toolbar function component takes an extra “theme” prop and pass it to the ThemedButton. It can become inconvenient if every single button in the app needs to know the theme because it would be required to pass through all components. But using context, we can avoid passing props for every component through intermediate elements.

                                                                We can understand it from the below example. Here, context passes a value into the component tree without explicitly threading it through every single component.

                                                                // Create a context for the current theme which is "light" as the default.  
                                                                
                                                                const ThemeContext = React.createContext('light');  
                                                                
                                                                  
                                                                
                                                                class App extends React.Component {  
                                                                
                                                                  render() {  
                                                                
                                                                    /* Use a ContextProvider to pass the current theme, which allows every component to read it, no matter how deep it is. Here, we are passing the "dark" theme as the current value.*/  
                                                                
                                                                  
                                                                
                                                                    return (  
                                                                
                                                                      <ThemeContext.Provider value="dark">  
                                                                
                                                                        <Toolbar />  
                                                                
                                                                      </ThemeContext.Provider>  
                                                                
                                                                    );  
                                                                
                                                                  }  
                                                                
                                                                }  
                                                                
                                                                  
                                                                
                                                                // Now, it is not required to pass the theme down explicitly for every component.  
                                                                
                                                                function Toolbar(props) {  
                                                                
                                                                  return (  
                                                                
                                                                    <div>  
                                                                
                                                                      <ThemedButton />  
                                                                
                                                                    </div>  
                                                                
                                                                  );  
                                                                
                                                                }  
                                                                
                                                                  
                                                                
                                                                class ThemedButton extends React.Component {  
                                                                
                                                                  static contextType = ThemeContext;  
                                                                
                                                                  render() {  
                                                                
                                                                    return <Button theme={this.context} />;  
                                                                
                                                                  }  
                                                                
                                                                }

                                                                React Context API

                                                                The React Context API is a component structure, which allows us to share data across all levels of the application. The main aim of Context API is to solve the problem of prop drilling (also called “Threading”). The Context API in React are given below.

                                                                1. React.createContext
                                                                2. Context.provider
                                                                3. Context.Consumer
                                                                4. Class.contextType

                                                                React.createContext

                                                                It creates a context object. When React renders a component which subscribes to this context object, then it will read the current context value from the matching provider in the component tree.

                                                                Syntax

                                                                const MyContext = React.createContext(defaultValue);  

                                                                When a component does not have a matching Provider in the component tree, it returns the defaultValue argument. It is very helpful for testing components isolation (separately) without wrapping them.

                                                                Context.Provider

                                                                Every Context object has a Provider React component which allows consuming components to subscribe to context changes. It acts as a delivery service. When a consumer component asks for something, it finds it in the context and provides it to where it is needed.

                                                                Syntax

                                                                <MyContext.Provider value={/* some value */}>  

                                                                It accepts the value prop and passes to consuming components which are descendants of this Provider. We can connect one Provider with many consumers. Context Providers can be nested to override values deeper within the component tree. All consumers that are descendants of a Provider always re-render whenever the Provider’s value prop is changed. The changes are determined by comparing the old and new values using the same algorithm as Object.is algorithm.

                                                                Context.Consumer

                                                                It is the React component which subscribes to the context changes. It allows us to subscribe to the context within the function component. It requires the function as a component. A consumer is used to request data through the provider and manipulate the central data store when the provider allows it.

                                                                Syntax

                                                                <MyContext.Consumer>  
                                                                
                                                                       {value => /* render something which is based on the context value */}  
                                                                
                                                                </MyContext.Consumer>  

                                                                  The function component receives the current context value and then returns a React node. The value argument which passed to the function will be equal to the value prop of the closest Provider for this context in the component tree. If there is no Provider for this context, the value argument will be equal to the defaultValue which was passed to createContext().

                                                                  Class.contextType

                                                                  The contextType property on a class used to assign a Context object which is created by React.createContext(). It allows you to consume the closest current value of that Context type using this.context. We can reference this in any of the component life-cycle methods, including the render function.

                                                                  Note: We can only subscribe to a single context using this API. If we want to use the experimental public class field’s syntax, we can use a static class field to initialize the contextType.

                                                                  React Context API Example

                                                                  Step1 Create a new React app using the following command.

                                                                  $ npx create-react-app mycontextapi  

                                                                  Step2 Install bootstrap CSS framework using the following command.

                                                                  $ npm install react-bootstrap bootstrap --save    

                                                                  Step3 Add the following code snippet in the src/APP.js file.

                                                                  import React, { Component } from 'react';  
                                                                  
                                                                  import 'bootstrap/dist/css/bootstrap.min.css';  
                                                                  
                                                                    
                                                                  
                                                                  const BtnColorContext = React.createContext('btn btn-darkyellow');  
                                                                  
                                                                    
                                                                  
                                                                  class App extends Component {  
                                                                  
                                                                    render() {  
                                                                  
                                                                      return (  
                                                                  
                                                                        <BtnColorContext.Provider value="btn btn-info">  
                                                                  
                                                                          <Button />  
                                                                  
                                                                        </BtnColorContext.Provider>  
                                                                  
                                                                      );  
                                                                  
                                                                    }  
                                                                  
                                                                  }  
                                                                  
                                                                    
                                                                  
                                                                  function Button(props) {  
                                                                  
                                                                    return (  
                                                                  
                                                                    <div className="container">  
                                                                  
                                                                      <ThemedButton />      
                                                                  
                                                                    </div>  
                                                                  
                                                                    );  
                                                                  
                                                                  }  
                                                                  
                                                                    
                                                                  
                                                                  class ThemedButton extends Component {  
                                                                  
                                                                      
                                                                  
                                                                    static contextType = BtnColorContext;  
                                                                  
                                                                    render() {  
                                                                  
                                                                      return <button className={this.context} >  
                                                                  
                                                                        welcome to javatpoint  
                                                                  
                                                                      </button>;  
                                                                  
                                                                    }  
                                                                  
                                                                  }  
                                                                  
                                                                  export default App;

                                                                  In the above code snippet, we have created the context using React.createContext(), which returns the Context object. After that, we have created the wrapper component which returns the Provider component, and then add all the elements as children from which we want to access the context.

                                                                  output:

                                                                  When we run the React app, we will get the following screen.

                                                                  React Context
                                                                1. Code Splitting

                                                                  The React app bundled their files using tools like Webpack or Browserfy. Bundling is a process which takes multiple files and merges them into a single file, which is called a bundle. The bundle is responsible for loading an entire app at once on the webpage. We can understand it from the below example.

                                                                  App.js

                                                                  import { add } from './math.js';  
                                                                  
                                                                    
                                                                  
                                                                  console.log(add(16, 26)); // 42  

                                                                    math.js

                                                                    export function add(a, b) {  
                                                                    
                                                                      return a + b;  
                                                                    
                                                                    } 

                                                                      Bundle file as like below:

                                                                      function add(a, b) {  
                                                                      
                                                                        return a + b;  
                                                                      
                                                                      }  
                                                                      
                                                                        
                                                                      
                                                                      console.log(add(16, 26)); // 42  

                                                                        As our app grows, our bundle will grow too, especially when we are using large third-party libraries. If the bundle size gets large, it takes a long time to load on a webpage. For avoiding the large bundling, it?s good to start ?splitting? your bundle.

                                                                        React 16.6.0, released in October 2018, and introduced a way of performing code splitting. Code-Splitting is a feature supported by Webpack and Browserify, which can create multiple bundles that can be dynamically loaded at runtime.

                                                                        Code splitting uses React.lazy and Suspense tool/library, which helps you to load a dependency lazily and only load it when needed by the user.

                                                                        The code splitting improves:

                                                                        • The performance of the app
                                                                        • The impact on memory
                                                                        • The downloaded Kilobytes (or Megabytes) size

                                                                        React.lazy

                                                                        The best way for code splitting into the app is through the dynamic import() syntax. The React.lazy function allows us to render a dynamic import as a regular component.

                                                                        Before

                                                                        import ExampleComponent from './ExampleComponent';  
                                                                        
                                                                          
                                                                        
                                                                        function MyComponent() {  
                                                                        
                                                                          return (  
                                                                        
                                                                            <div>  
                                                                        
                                                                              <ExampleComponent />  
                                                                        
                                                                            </div>  
                                                                        
                                                                          );  
                                                                        
                                                                        } 

                                                                          After

                                                                          const ExampleComponent = React.lazy(() => import('./ExampleComponent'));  
                                                                          
                                                                            
                                                                          
                                                                          function MyComponent() {  
                                                                          
                                                                            return (  
                                                                          
                                                                              <div>  
                                                                          
                                                                                <ExampleComponent />  
                                                                          
                                                                              </div>  
                                                                          
                                                                            );  
                                                                          
                                                                          }

                                                                          The above code snippet automatically loads the bundle which contains the ExampleComponent when the ExampleComponent gets rendered.

                                                                          Suspense

                                                                          If the module which contains the ExampleComponent is not yet loaded by the function component(MyComponent), then we need to show some fallback content while we are waiting for it to load. We can do this using the suspense component. In other words, the suspense component is responsible for handling the output when the lazy component is fetched and rendered.

                                                                          const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));  
                                                                          
                                                                            
                                                                          
                                                                          function MyComponent() {  
                                                                          
                                                                            return (  
                                                                          
                                                                              <div>  
                                                                          
                                                                                <Suspense fallback={<div>Loading...</div>}>  
                                                                          
                                                                                  <ExampleComponent />  
                                                                          
                                                                                </Suspense>  
                                                                          
                                                                              </div>  
                                                                          
                                                                            );  
                                                                          
                                                                          }

                                                                          The fallback prop accepts the React elements which you want to render while waiting for the component to load. We can combine multiple lazy components with a single Suspense component. It can be seen in the below example.

                                                                          const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));  
                                                                          
                                                                          const ExamComponent = React.lazy(() => import('./ ExamComponent'));  
                                                                          
                                                                            
                                                                          
                                                                          function MyComponent() {  
                                                                          
                                                                            return (  
                                                                          
                                                                              <div>  
                                                                          
                                                                                <Suspense fallback={<div>Loading...</div>}>  
                                                                          
                                                                                  <section>  
                                                                          
                                                                                    <ExampleComponent />  
                                                                          
                                                                                    <ExamComponent />  
                                                                          
                                                                                  </section>  
                                                                          
                                                                                </Suspense>  
                                                                          
                                                                              </div>  
                                                                          
                                                                            );  
                                                                          
                                                                          }

                                                                          Note: React.lazy and Suspense components are not yet available for server-side rendering. For code-splitting in a server-rendered app, it is recommended to use Loadable Components.

                                                                          Error boundaries

                                                                          If any module fails to load, for example, due to network failure, we will get an error. We can handle these errors with Error Boundaries. Once we have created the Error Boundary, we can use it anywhere above our lazy components to display an error state.

                                                                          import MyErrorBoundary from './MyErrorBoundary';  
                                                                          
                                                                          const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));  
                                                                          
                                                                          const ExamComponent = React.lazy(() => import('./ ExamComponent'));  
                                                                          
                                                                            
                                                                          
                                                                          const MyComponent = () => (  
                                                                          
                                                                            <div>  
                                                                          
                                                                              <MyErrorBoundary>  
                                                                          
                                                                                <Suspense fallback={<div>Loading...</div>}>  
                                                                          
                                                                                  <section>  
                                                                          
                                                                                    <ExampleComponent />  
                                                                          
                                                                                    <ExamComponent />  
                                                                          
                                                                                  </section>  
                                                                          
                                                                                </Suspense>  
                                                                          
                                                                              </MyErrorBoundary>  
                                                                          
                                                                            </div>  
                                                                          
                                                                          );  

                                                                            Route-based code splitting

                                                                            It is very tricky to decide where we introduce code splitting in the app. For this, we have to make sure that we choose the place which will split the bundles evenly without disrupting the user experience.

                                                                            The route is the best place to start the code splitting. Route based code splitting is essential during the page transitions on the web, which takes some amount of time to load. Here is an example of how to setup route-based code splitting into the app using React Router with React.lazy.

                                                                            import { Switch, BrowserRouter as Router, Route} from 'react-router-dom';  
                                                                            
                                                                            import React, { Suspense, lazy } from 'react';  
                                                                            
                                                                              
                                                                            
                                                                            const Home = lazy(() => import('./routes/Home'));  
                                                                            
                                                                            const About = lazy(() => import('./routes/About'));  
                                                                            
                                                                            const Contact = lazy(() => import('./routes/Contact'));  
                                                                            
                                                                              
                                                                            
                                                                            const App = () => (  
                                                                            
                                                                              <Router>  
                                                                            
                                                                                <Suspense fallback={<div>Loading...</div>}>  
                                                                            
                                                                                  <Switch>  
                                                                            
                                                                                    <Route exact path="/" component={Home}/>  
                                                                            
                                                                                    <Route path="/about" component={About}/>  
                                                                            
                                                                                    <Route path="/contact" component={Contact}/>  
                                                                            
                                                                                  </Switch>  
                                                                            
                                                                                </Suspense>  
                                                                            
                                                                              </Router>  
                                                                            
                                                                            ); 

                                                                              Named Export

                                                                              Currently, React.lazy supports default exports only. If any module you want to import using named exports, you need to create an intermediate module that re-exports it as the default. We can understand it from the below example.

                                                                              ExampleComponents.js

                                                                              export const MyFirstComponent = /* ... */;  
                                                                              
                                                                              export const MySecondComponent = /* ... */;  

                                                                                MyFirstComponent.js

                                                                                export { MyFirstComponent as default } from "./ExampleComponents.js";  

                                                                                MyApp.js

                                                                                import React, { lazy } from 'react';  
                                                                                
                                                                                const MyFirstComponent = lazy(() => import("./MyFirstComponent.js"));
                                                                              1. Higher-Order Components

                                                                                It is also known as HOC. In React, HOC is an advanced technique for reusing component logic. It is a function that takes a component and returns a new component. According to the official website, it is not the feature(part) in React API, but a pattern that emerges from React compositional nature. They are similar to JavaScript functions used for adding additional functionalities to the existing component.

                                                                                A higher order component function accepts another function as an argument. The map function is the best example to understand this. The main goal of this is to decompose the component logic into simpler and smaller functions that can be reused as you need.

                                                                                Syntax

                                                                                const NewComponent = higherOrderComponent(WrappedComponent);  

                                                                                We know that component transforms props into UI, and a higher-order component converts a component another component and allows to add additional data or functionality into this. Hocs are common in third-party libraries. The examples of HOCs are Redux’s connect and Relay’s createFragmentContainer.

                                                                                Now, we can understand the working of HOCs from the below example.

                                                                                //Function Creation  
                                                                                
                                                                                function add (a, b) {  
                                                                                
                                                                                  return a + b  
                                                                                
                                                                                }  
                                                                                
                                                                                function higherOrder(a, addReference) {  
                                                                                
                                                                                  return addReference(a, 20)  
                                                                                
                                                                                }  
                                                                                
                                                                                //Function call  
                                                                                
                                                                                higherOrder(30, add) // 50 

                                                                                  In the above example, we have created two functions add() and higherOrder(). Now, we provide the add() function as an argument to the higherOrder() function. For invoking, rename it addReference in the higherOrder() function, and then invoke it.

                                                                                  Here, the function you are passing is called a callback function, and the function where you are passing the callback function is called a higher-order(HOCs) function.

                                                                                  Example

                                                                                  Create a new file with the name HOC.js. In this file, we have made one function HOC. It accepts one argument as a component. Here, that component is App.

                                                                                  HOC.js

                                                                                  import React, {Component} from 'react';  
                                                                                  
                                                                                    
                                                                                  
                                                                                  export default function Hoc(HocComponent){  
                                                                                  
                                                                                      return class extends Component{  
                                                                                  
                                                                                          render(){  
                                                                                  
                                                                                              return (  
                                                                                  
                                                                                                  <div>  
                                                                                  
                                                                                                      <HocComponent></HocComponent>  
                                                                                  
                                                                                                  </div>  
                                                                                  
                                                                                    
                                                                                  
                                                                                              );  
                                                                                  
                                                                                          }  
                                                                                  
                                                                                      }   
                                                                                  
                                                                                  }

                                                                                  Now, include HOC.js file into the App.js file. In this file, we need to call the HOC function.

                                                                                  App = Hoc(App);  

                                                                                  The App component wrapped inside another React component so that we can modify it. Thus, it becomes the primary application of the Higher-Order Components.

                                                                                  App.js

                                                                                  import React, { Component } from 'react';  
                                                                                  
                                                                                  import Hoc from './HOC';  
                                                                                  
                                                                                    
                                                                                  
                                                                                  class App extends Component {  
                                                                                  
                                                                                    render() {  
                                                                                  
                                                                                      return (  
                                                                                  
                                                                                        <div>  
                                                                                  
                                                                                          <h2>HOC Example</h2>  
                                                                                  
                                                                                          JavaTpoint provides best CS tutorials.  
                                                                                  
                                                                                        </div>  
                                                                                  
                                                                                      )  
                                                                                  
                                                                                    }  
                                                                                  
                                                                                  }  
                                                                                  
                                                                                  App = Hoc(App);  
                                                                                  
                                                                                  export default App;

                                                                                  Output

                                                                                  When we execute the above file, it will give the output as below screen.

                                                                                  React Higher-Order Components

                                                                                  Higher-Order Component Conventions

                                                                                  • Do not use HOCs inside the render method of a component.
                                                                                  • The static methods must be copied over to have access to them. You can do this using hoist-non-react-statics package to automatically copy all non-React static methods.
                                                                                  • HOCs does not work for refs as ‘Refs’ does not pass through as a parameter or argument. If you add a ref to an element in the HOC component, the ref refers to an instance of the outermost container component, not the wrapped component.