These resources offer a comprehensive introduction to React JS, covering its fundamental concepts like component architecture, JSX, virtual DOM, state management (including Redux), props, and event handling. They also discuss React Router for navigation, the use of hooks, and performance optimization techniques. Furthermore, the material outlines React’s lifecycle methods, conditional rendering, debugging, testing, and provides guidance on becoming a React developer, including prerequisites and common interview questions. The advantages and applications of React, alongside comparisons with Angular and React Native, are also explored.
React Fundamentals Study Guide
Quiz
- Explain the concept of state in React components. How is it initialized and updated?
- What are props in React? How are they different from state, and how are they passed between components?
- Describe the purpose of event handlers in React. Provide an example of how an event handler is defined and used.
- What is JSX? Why is it used in React, and how does it relate to JavaScript and HTML?
- Explain the concept of components in React. What are the two main types of components, and what are their key differences?
- What is conditional rendering in React? Describe two common methods for implementing it.
- Explain the component lifecycle in React. Briefly describe the purpose of componentDidMount and componentWillUnmount.
- What are keys in React lists? Why are they important, and what happens if they are not used correctly?
- Define the term “props” in React. What is this.props.children, and what are its possible values?
- Describe the purpose of setState in React. Why should you not directly modify the state object?
Answer Key
- State in React components is a way to manage data that can change over time and affects the component’s rendering. It is initialized within the component’s constructor using this.state = { /* initial values */ }. State is updated asynchronously using the this.setState() method, which triggers a re-render of the component.
- Props (short for properties) are read-only data passed from a parent component to its child components. They are different from state because state is managed within the component itself and can be changed by the component, while props are external data passed down. Props are passed by including attributes with values on the child component when it is rendered in the parent.
- Event handlers in React are functions that are called in response to user interactions or other events, such as clicks, form submissions, or mouse movements. An event handler is typically defined as a method within a component and then passed as a prop to a JSX element. For example: <button onClick={this.handleClick}>Click Me</button>.
- JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like structures directly within your JavaScript code. It is used in React to describe the user interface of components in a declarative way, making the code easier to read and understand. JSX is transformed into regular JavaScript function calls by tools like Babel.
- Components in React are reusable and independent pieces of UI logic. The two main types are functional components (plain JavaScript functions that return JSX) and class components (ES6 classes that extend React.Component and can have state and lifecycle methods). Functional components are simpler and often used for presentational purposes, while class components are more feature-rich and can manage stateful logic.
- Conditional rendering in React is the process of displaying different elements or components based on certain conditions. Two common methods are using if/else statements or ternary operators (condition ? <ComponentA /> : <ComponentB />) within the render method, or using short-circuit evaluation (condition && <ComponentA />).
- The component lifecycle in React refers to the series of events that occur from the moment a component is created and mounted onto the DOM to when it is unmounted and removed from the DOM. componentDidMount is a lifecycle method that is invoked immediately after a component is mounted (inserted into the tree). It is often used for tasks like fetching data or setting up subscriptions. componentWillUnmount is invoked immediately before a component is unmounted and destroyed. It is used for cleanup tasks like canceling network requests or removing event listeners.
- Keys in React lists are special string attributes that should be included when mapping over an array to create a list of elements. They are important because they help React identify which items in the list have changed, been added, or been removed. Without unique keys, React may not be able to efficiently update the DOM, potentially leading to performance issues and incorrect component state.
- Props in React are a mechanism for passing data from a parent component to its child components. this.props.children refers to any elements or components that are passed as children within the opening and closing tags of a component when it is rendered in its parent. Its possible values can be a single React element, an array of React elements, or undefined if no children are passed.
- setState in React is a method used in class components to update the component’s state. It accepts an object or a function that returns an object and schedules an update to the component’s state, eventually triggering a re-render. You should not directly modify the state object (e.g., this.state.count = 5) because React may not recognize the change and not re-render the component correctly. setState ensures that the component and its children are re-rendered with the updated state.
Essay Format Questions
- Discuss the benefits of using a component-based architecture like React for building user interfaces. Explain how components promote reusability, maintainability, and scalability in web development.
- Compare and contrast state management in functional components using hooks (like useState and useReducer) with state management in class components using this.state and this.setState. When might you choose one approach over the other?
- Explain the flow of data in a typical React application that utilizes props and state. Describe how data originates, how it is passed down through the component tree, and how user interactions can lead to data changes.
- Discuss the role and importance of lifecycle methods in class components. Choose three lifecycle methods (e.g., componentDidMount, componentDidUpdate, componentWillUnmount) and explain the common use cases for each.
- Analyze the different approaches to conditional rendering in React (if/else, ternary operators, short-circuit evaluation, element variables). Provide scenarios where each approach might be most suitable and discuss their advantages and disadvantages.
Glossary of Key Terms
- Component: A reusable and independent building block of a React user interface, encapsulating its own logic and rendering.
- State: A JavaScript object that holds data local to a component and controls its behavior and rendering over time. It is mutable and managed within the component.
- Props (Properties): Data passed from a parent component to a child component. They are immutable from the child’s perspective.
- JSX (JavaScript XML): A syntax extension for JavaScript that allows embedding HTML-like structures within JavaScript code, used in React to describe UI.
- Event Handler: A function that is executed in response to a specific event (e.g., user interaction) occurring on a React element.
- Conditional Rendering: The process of displaying different UI elements or components based on certain conditions in a React application.
- Lifecycle Methods: Special methods in class components that are invoked at different stages of a component’s existence (mounting, updating, unmounting).
- Keys: Special string attributes assigned to elements in a list rendered by React, used to uniquely identify each item for efficient updates.
- setState(): A method used in class components to update the component’s state and trigger a re-render of the component and its children.
- Functional Component: A simpler type of React component that is essentially a JavaScript function that accepts props as arguments and returns JSX.
- Class Component: A more feature-rich type of React component that is an ES6 class, can have state and lifecycle methods, and uses a render() method to return JSX.
- this.props.children: A special prop that refers to any content (JSX elements, other components) passed between the opening and closing tags of a component.
- componentDidMount(): A lifecycle method invoked immediately after a component has been mounted to the DOM.
- componentWillUnmount(): A lifecycle method invoked immediately before a component is unmounted and destroyed.
- Hook: A special function in React that lets you “hook into” React state and lifecycle features from functional components. Examples include useState and useEffect.
Briefing Document: React Fundamentals and Mario Game Development
This document provides a detailed review of the main themes and important ideas presented in the provided sources, which cover fundamental concepts of React.js and a practical example of building a Mario game using React.
Part 1: React Fundamentals
This section outlines the core concepts of React.js as explained in the first source.
Main Themes:
- Ease of Learning: React is presented as easier to learn compared to other JavaScript frameworks like Angular.
- “learning react is easier than learning other JavaScript Frameworks”
- React’s simplicity is attributed to its component-based architecture, simpler file structure, flexible component model, and shorter dependency list.
- Core Concepts: The source emphasizes several fundamental building blocks of React applications.
- Components: The UI is built by composing reusable and independent pieces of code called components. Examples given include app.js, counter.js, and index.js.
- “all the files that you can see inside the source are components of the real so app.js is one component counter. GS is one component index.js is one company”
- JSX (JavaScript XML): React uses a syntax extension that allows writing HTML-like structures within JavaScript code.
- “this right here the code that we are able to see is basically jsx syntax so basically this is a JavaScript code but we have written HTML inside the Javascript file so this is called GSX”
- Props (Properties): Props are used to pass data from parent components to child components. They are read-only from the child’s perspective.
- “react uses props to pass attributes from parent components to child components”
- State: State allows creating dynamic and interactive components. It is private to a component and can be updated to trigger re-renders.
- “UST state zero initializes account State variable with the initial value of zero and after that count holds the current count and set count is a function that updates the value so state in react is persistent across renders meaning count will retain the value until it’s updated by set count”
- Event Handlers: These are functions that respond to user interactions (e.g., clicks) and can update the component’s state. Examples include increment, decrement, and reset functions.
- “these functions are used to update the count State based on the user actions first of all we have the increment so it increases the count by five each time it is called”
- Styling: CSS is used to style React components. The example mentions style.css and various CSS properties and techniques like font family, display, justify content, alignment, height, background color, hover effects, animations, keyframes, and media queries.
- Component Lifecycle: React components have a lifecycle with different phases (initial, update, unmount), and lifecycle methods are called at specific points.
- Conditional Rendering: React allows rendering different components or parts of the UI based on certain conditions. Methods include if/else statements, element variables, ternary operators, and short-circuit operators.
- “conditional rendering is nothing but if a given statement is true then the if statement executes or else the L statement will execute”
- Preventing Rendering: Components can prevent rendering by returning null from their render method.
- “to do this return null instead of its render output”
- Refs (References): Refs provide a way to access DOM elements or component instances directly.
- Keys: Keys are used to uniquely identify elements in lists, helping React optimize rendering.
- React Router: A library for adding navigation and routing to React applications, keeping the UI in sync with the URL. Different types include BrowserRouter and HashRouter.
- Context API: A way to share state between components without explicitly passing props through every level of the component tree. Hooks like useContext are used to consume context values.
- useReducer Hook: An alternative to useState for more complex state management within functional components, similar to Redux in concept.
- useEffect Hook: Used for performing side effects in functional components (e.g., data fetching, subscriptions). It includes a cleanup function.
- useLayoutEffect Hook: Similar to useEffect but runs synchronously after all DOM mutations. Should be used cautiously to avoid performance issues.
- Redux: A pattern and library for managing and updating application state in a predictable way, especially for complex applications with global state. Key components include Store, Actions, Reducers, and Dispatcher. Unidirectional data flow is a core principle.
- Testing: React applications can be tested using frameworks like Jest and Enzyme. Different types of testing include component testing (snapshot testing), integration testing, and end-to-end testing.
- Version Control with Git: Git is used to track changes in code and collaborate with other developers. Common Git commands like init, add, commit, push, pull, branch, and checkout are mentioned.
Important Ideas and Facts:
- React is a library focused on the view layer of an application.
- Components are the fundamental building blocks of React UIs.
- JSX makes it easier to write and understand UI structures within JavaScript.
- Props are immutable from the child component’s perspective.
- State changes trigger re-renders of the component and its children.
- Lifecycle methods allow performing actions at specific stages of a component’s existence.
- Conditional rendering enables dynamic UIs based on application logic.
- Refs provide a way to interact directly with the DOM or component instances when necessary.
- Keys are crucial for efficient rendering of dynamic lists.
- React Router enables building single-page applications with navigation.
- Context API offers a way to avoid prop drilling for shared state.
- useReducer is suitable for managing complex state logic.
- useEffect is the primary hook for handling side effects.
- useLayoutEffect should be used for DOM measurements or synchronous layout adjustments.
- Redux provides a centralized store for managing global application state.
- Testing is essential for ensuring the reliability of React applications.
- Git is a widely used version control system for collaborative development.
Quotes:
- (Regarding state persistence): “state in react is persistent across renders meaning count will retain the value until it’s updated by set count”
- (Regarding the purpose of event handlers): “these functions are used to update the count State based on the user actions”
- (Defining components): “all the files that you can see inside the source are components of the real so app.js is one component counter. GS is one component index.js is one company”
- (Defining JSX): “this right here the code that we are able to see is basically jsx syntax so basically this is a JavaScript code but we have written HTML inside the Javascript file so this is called GSX”
- (Purpose of props): “react uses props to pass attributes from parent components to child components”
- (Purpose of conditional rendering): “conditional rendering is nothing but if a given statement is true then the if statement executes or else the L statement will execute”
- (Preventing rendering): “to do this return null instead of its render output”
- (Flux as data flow management): “flux is a pattern for managing the data flow in your application”
- (Unidirectional data flow in React): “data flows only in One Direction”
- (Keys for unique identification): “keys are the elements which helps react to identify the components uniquely”
- (Redux for global state): “Redux helps you manage Global state that is actually the state that is needed across many parts of your application”
- (Jest as a testing framework): “zest is a fast testing framework it act as a test Runner assert library and moing library”
- (Enzyme for React testing): “enzyme is a JavaScript test utility for react that make it easier to assert manipulate and derse your react component output”
- (Git for version control): “Version Control is one that record changes for document computer program large website and other collection of information over time it allow multiple user to manage multiple revision of same unit of information”
Part 2: Mario Game Development with React
This section details the structure and implementation of a Mario game built using React, as described in the second source.
Main Themes:
- Component-Based Architecture in Practice: The game is built using a modular approach with numerous components organized into atoms and molecules directories within the components folder.
- atoms: Basic building blocks like Birds, Bricks, Clouds, KeyMessage, Obstacle, and Sun.
- molecules: Compositions of atoms or other molecules, representing more complex UI elements like Footer, LoadingScreen, Mario, Corrector (likely character controller), MobileControls, Title, and Score.
- Asset Management: The game utilizes an asset directory to store audio files, fonts, and images (including GIFs for animation).
- “in this there is a section named esset in this we have included the audio font and the images that we are going to use”
- State Management (Likely with Redux): The Obstacle component explicitly imports and uses Redux hooks (useDispatch, useSelector), suggesting that Redux is used for managing the game state (e.g., game running status, speed, object positions).
- “It also Imports Redux Hook from the state management so after that dis patch is used to send actions to the Redux store is playay and speed are selected from the Redux state”
- Animation Techniques: Components like Birds, Bricks, and Clouds use CSS animations (defined with @keyframes and potentially triggered by state changes using class names like bird animate, brick animate). The Obstacle component dynamically adjusts animation duration based on game speed.
- “if is ready is true it adds the class bird animate which likely triggers an animation”
- “The style props adjust the animation duration based on the speed making the animation faster or slower depending upon the game’s current speed”
- Event Handling for User Interaction: The KeyMessage component indicates that the “Enter key” starts the game and the “space key” is used for jumping, implying the use of event listeners to capture keyboard input and trigger game actions (likely managed within the Mario or a game controller component).
- “inside this we have basically created one press container and we have given two paragraphs including Enter key and space key so here Enter key is for starting the game and space key is for jump”
- Audio Integration: The Mario component imports and likely uses audio files for jump, death sounds, and background music, managed using the useMemo hook for optimization.
- “audio files for jump death sound and various hooks from the react and reds so after that this used dispatch hook allows dispatching actions to the redex store several State values are selected from the redex store to manage the game State such as whether Mario is dead the game is loading or the Mario’s position and the Dimensions”
- “for this we are using use memo hook to create audio objects for jump die and background music this ensure that these objects are only created once optimizing the performance”
- Collision Detection: The Mario component retrieves the position and dimensions of obstacles from the Redux store to implement collision detection logic.
- “these selectors retrieve the position and dimension of two obstacles allowing for the Collision detection”
- Scorekeeping: The Score component manages the current score, last score, and high score, potentially using localStorage for persistence. It uses useEffect with a timer to increment the score while the game is playing.
- “the score shows the current score from the RCT store and the last score shows the last score recorded and the play is basically a Boolean indicating if the game is currently being played die is basically a Boolean indicating if the game is over and dispatch is a function that is used to dispatch the action of the Redux store”
- “this basically initializes the state variable high score it retrieves the high score from local storage passing it as an integer or defaults to zero if the high score is not found”
- “this use effect runs whenever the dependencies change that means incrementing the score if the game is being played or not over it sets the time out to increment the score by one to every milliseconds and then updating the last score and the high score”
- Loading Screen: A LoadingScreen component suggests that the game handles loading states, potentially waiting for assets to load before starting.
- Mobile Controls: The inclusion of a MobileControls component indicates support for touch-based input on mobile devices.
Important Ideas and Facts:
- The game demonstrates a real-world application of React’s component-based architecture for organizing a complex UI and game logic.
- The separation of components into atoms and molecules promotes reusability and maintainability.
- The use of Redux for state management suggests a need to manage global game state across multiple components.
- CSS animations and dynamic styling based on game state create visual effects and responsiveness.
- Event listeners are crucial for making the game interactive.
- Audio feedback enhances the user experience.
- Collision detection is a fundamental aspect of gameplay.
- Scorekeeping provides a way to track player progress.
- Handling loading states ensures a smoother user experience.
- Mobile controls extend the game’s reach to different platforms.
- The index.js files within the components, atoms, and molecules directories serve as central export points for the components within those folders.
Quotes:
- (Component organization): “inside this components we have one section that is atoms in this we have included all the components that are being used in this game for example we are using Birds bricks clouds key message obstacle sun and all so after this we have this molecules in this we have included the footer the loading screen Mario the corrector and the mobile controls again we have included the title and the score”
- (Asset inclusion): “in this there is a section named esset in this we have included the audio font and the images that we are going to use”
- (Redux usage in Obstacle): “It also Imports Redux Hook from the state management so after that dis patch is used to send actions to the Redux store is playay and speed are selected from the Redux state”
- (Animation in Birds): “if is ready is true it adds the class bird animate which likely triggers an animation”
- (Key bindings in KeyMessage): “Enter key is for starting the game and space key is for jump”
- (Audio in Mario): “audio objects for jump die and background music this ensure that these objects are only created once optimizing the performance”
- (Score and localStorage): “it retrieves the high score from local storage passing it as an integer or defaults to zero if the high score is not found”
- (Component export in components/index.js): “each Line Imports the component of specific file path for example bird component is imported from the birds file the imported components are presumbly react components that will be used in the application to render the different parts of the UI and after that this line exports all the imported components into single object by doing this it allows other modules to import any of these components easily from one Central File instead of importing each of them individually from their respective files”
This detailed briefing document summarizes the key concepts and practical application of React.js as presented in the provided sources. It highlights the fundamental principles of React development and showcases how these principles are applied in the creation of an interactive game.
React Core Concepts and Mario Game Structure
1. What are the core concepts of React demonstrated in the counter app example?
The counter app demonstrates three core concepts of React:
- State: State is data that can change over time and affects the component’s behavior and rendering. In the counter app, the count variable, initialized to zero, represents the component’s state. The setCount function is used to update this state. React state is persistent across renders, meaning the count value is retained until explicitly updated.
- Properties (Props): Although not explicitly manipulated within the counter app itself, the explanation mentions that components can receive data from parent components through props. Props are read-only and are used to pass data down the component tree.
- Event Listeners: Event listeners are functions that respond to user interactions or other events. The counter app defines event handlers like increment, decrement, and reset. These functions use setCount to update the component’s state in response to button clicks, making the component interactive.
2. What is JSX and why is it a core concept in React?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write HTML-like structures directly within their JavaScript code. In React, JSX is used to describe the user interface of components. It is a core concept because:
- Declarative UI: JSX makes it easier to visualize and describe the desired UI structure, as it closely resembles HTML.
- Component Composition: JSX is used within the render method of React components to define what they should output. This facilitates the composition of complex UIs from smaller, reusable components.
- Embedding JavaScript: JSX allows embedding JavaScript expressions within the HTML-like syntax using curly braces {}. This enables dynamic rendering based on component state and props.
- Compilation: JSX code is not directly understood by browsers. It is transformed into standard JavaScript code (specifically, calls to React.createElement) by a build tool like Babel.
3. How does React handle styling of components?
React can handle styling through CSS. The example project includes a style.css file where styles are defined for various HTML elements and React components. These styles are then applied by importing the CSS file into the corresponding JavaScript component files. The example demonstrates styling for the body, app, counter, and button elements, including hover effects. React also supports inline styles (applied directly to elements using a JavaScript object) and CSS-in-JS libraries, although these are not shown in this basic example. Media queries can also be used within the CSS files to create responsive designs.
4. What is the role of components in React, according to the sources?
According to the sources, components are the fundamental building blocks of React applications.
- Modularity: React applications are structured as a collection of independent and reusable components. Each file within the src directory (like app.js and counter.js) represents a component.
- Reusability: Components can be used multiple times throughout the application, promoting code reuse and maintainability.
- UI Decomposition: Components allow developers to break down complex user interfaces into smaller, manageable pieces. This makes it easier to develop, test, and understand the application’s structure.
- Data Management: Components manage their own state (data that can change) and receive data from parent components via props. They define how data is rendered and how user interactions are handled.
5. Can you describe the structure of the Mario game project in terms of components and assets?
The Mario game project is structured into two main sections within the src directory:
- assets: This section contains the static resources used by the game, including:
- audio: Sound files for game events.
- font: Custom fonts for text elements.
- images: Sprite sheets and individual images for characters, backgrounds, and other game elements.
- components: This section is further divided into:
- atoms: These are the smallest, indivisible UI elements used in the game. Examples include:
- Birds: Renders and animates birds in the background.
- Bricks: Renders and potentially animates brick elements.
- Clouds: Renders and animates clouds in the sky.
- KeyMessage: Displays instructions for game controls (Enter to start, Space to jump).
- Obstacle: Renders and manages the movement and collision detection of game obstacles.
- Sun: Renders the sun in the game’s background.
- molecules: These are compositions of one or more atoms, forming more complex UI elements or game entities. Examples include:
- Footer: Displays copyright information.
- LoadingScreen: Shows a loading animation.
- Mario: Represents and handles the logic and rendering of the Mario character, including movement, jumping, and collision detection.
- TheCorrector: Likely related to game logic or interactions.
- MobileControls: Provides on-screen buttons for mobile users to control Mario.
- Title: Displays the game’s title and logo.
- Score: Manages and displays the player’s score and high score.
The project also has index.js files within both atoms and molecules directories, which serve to import and then export all the components within those respective folders, providing a convenient way to import them elsewhere in the application.
6. How does the Mario game handle animation and movement of game elements like birds and obstacles?
The Mario game handles animation and movement using a combination of CSS animations and JavaScript logic within the React components:
- CSS Animations: Components like Birds, Bricks, and Clouds utilize CSS animations defined in their respective .css files. The JavaScript components (Birds.js, Bricks.js, Clouds.js) use React’s useState and useEffect hooks to conditionally apply CSS classes (e.g., bird animate, brick animate, cloud animate) to the elements. These classes trigger the animations defined using @keyframes in the CSS. The useEffect hook often listens for the document’s load event to ensure animations start after the page is fully loaded.
- JavaScript-based Movement and Updates: The Obstacle component uses JavaScript and React’s useEffect hook, along with Redux for state management, to handle the movement and positioning of obstacles. An interval (set to every 100 milliseconds) is used to periodically:
- Access the current dimensions and positions of the obstacle elements in the DOM using useRef and getBoundingClientRect().
- Dispatch actions to the Redux store to update the obstacles’ state (height, left, top, width).
- The animation speed of the obstacles is controlled by the speed value from the Redux store. The Obstacle.css file likely defines CSS animations (obstacle1-move, obstacle2-move), and the animation-duration style is dynamically adjusted based on the speed prop.
- Mario’s Movement and Collision: The Mario component also uses state, event listeners (for keyboard input), and likely Redux to manage its movement (jumping) and collision detection with obstacles. Key presses trigger state updates, which in turn affect Mario’s position and animations (potentially through CSS classes or inline styles). Collision detection is performed by comparing the positions and dimensions of Mario and the obstacles (retrieved from the Redux store).
7. What role does Redux play in the Mario game project, based on the excerpt?
Based on the excerpt, Redux plays a significant role in managing the global state of the Mario game:
- Centralized State Management: Redux provides a centralized store to hold the application’s state, making it accessible to different components without the need for prop drilling through multiple levels.
- Game State: The Obstacle and Mario components both interact with the Redux store. The Obstacle component selects isPlay (indicating if the game is running) and speed from the store and dispatches actions to update the obstacles’ dimensions and positions. The Mario component also uses Redux hooks like useDispatch and useSelector to manage its state, such as whether Mario is dead (isDead), the game’s loading status (isLoading), and Mario’s position and dimensions.
- Collision Detection: The Mario component uses selectors to retrieve the position and dimensions of the obstacles from the Redux store, enabling collision detection logic.
- Score Management: The Score component also interacts with the Redux store. It selects the current score, lastScore, play status, and die status. It also dispatches actions to update the Redux store with the score and potentially the high score.
In summary, Redux in this project facilitates communication and data sharing between various game components (like Obstacle, Mario, and Score) by providing a single source of truth for the game’s state.
8. What are some advantages of using React, as highlighted in the introductory and concluding sections of “01.pdf”?
The introductory and concluding sections of “01.pdf” highlight several advantages of using React:
- Easy to Learn: React is presented as being easier to learn compared to other JavaScript frameworks like Angular. Its core concepts are relatively straightforward, focusing on components, JSX, props, state, and event listeners.
- Efficient, Declarative, and Flexible: React is described as efficient, allowing for optimized updates to the DOM. Its declarative nature means developers describe the desired UI state, and React handles the rendering. It also offers flexibility in how developers structure their applications.
- Component-Based Architecture: React’s component-based approach promotes modularity and reusability of code, making it easier to build and maintain complex UIs.
- Simpler File Structure and Component Model: React generally has a simpler file tree and a flexible component model, reducing the cognitive load on developers.
- Shorter Dependency List: Compared to some other frameworks, React tends to have fewer dependencies, simplifying project setup and management.
- Large and Active Community: While not explicitly stated in these excerpts, the popularity of React implies a large and active community, providing ample resources, support, and third-party libraries.
- Suitable for Businesses: Due to its simplicity and efficiency, businesses are increasingly inclined to use React for their web application development.
- Performance: React’s efficient rendering mechanisms (like the virtual DOM, though not detailed here) contribute to better application performance.
React JS: A Comprehensive Overview
React JS is a popular open-source JavaScript library developed by Facebook for building dynamic and interactive user interfaces. It is widely used for creating single-page applications where seamless performance and efficient UI updates are crucial. Known for its component-based architecture, React JS allows developers to build reusable UI elements, making development faster and more organized. It is considered an essential tool in today’s web ecosystem due to its flexibility and efficiency, powering many dynamic and interactive web applications.
Key aspects and features of React JS discussed in the sources include:
- Component-Based Architecture: UI is broken down into reusable, self-contained components, each with its own structure and behavior, allowing for independent functionality. Applications built with React are essentially trees of components.
- Virtual DOM: React uses a lightweight copy of the actual DOM. Instead of directly updating the real DOM, React updates the virtual DOM first, calculates the changes, and then updates only the necessary parts of the real DOM. This significantly improves performance by reducing the overhead of direct DOM manipulation. The virtual DOM works in three steps: rendering the entire UI in the virtual DOM, calculating the difference compared to the previous state, and then updating only the changed elements in the real DOM.
- JSX (JavaScript XML): It is an XML or HTML-like syntax used by React that extends ECMAScript, allowing HTML-like text to coexist with JavaScript code. JSX is transformed into standard JavaScript objects by pre-processors like Babel. It makes HTML codes easier to understand and can boost JavaScript’s performance. Browsers cannot read JSX directly and require transformation into JavaScript.
- One-way Data Binding (Unidirectional Data Flow): Unlike some frameworks with two-way data binding, React follows a single direction of data flow from parent to child components. This makes the code more stable, easier to debug, and predictable, ultimately improving application performance. Flux is an architectural pattern used by Facebook with React that enforces this unidirectional data flow, involving a dispatcher, store, actions, and views. Redux is a popular library for state management in React applications that also follows these principles with a single store, actions, and reducers.
- Server-Side Rendering (SSR): React allows for pre-rendering the initial state of components on the server. The server sends a fully rendered HTML page to the browser, leading to faster initial page load times and improved SEO.
- Component Lifecycle: React components have lifecycle methods that allow developers to control component behavior during different phases, such as mounting (initial rendering), updating (due to state or prop changes), and unmounting (removal from the DOM). Examples include componentDidMount and componentWillUnmount.
- React Hooks: Introduced in React 16.8, hooks are functions that allow developers to use state and other React features in functional components. They make it easier to share stateful logic between components and work with functional components without needing classes. Commonly used hooks include useState, useEffect, and useContext. Custom hooks can also be created for reusable logic.
- Props (Properties): These are read-only components that are passed down from parent to child components to supply data. Props must be kept pure (immutable), maintaining the unidirectional data flow.
- State: State is the heart of React components, representing the source of data that determines how a component renders and behaves. Unlike props, state is mutable and can create dynamic and interactive components. State is managed within the component itself using this.state and updated using this.setState(). Direct modification of state is discouraged.
- Keys: Keys provide a unique identity to components, especially when rendering lists of elements. They help React efficiently update and reorder elements in the DOM.
- Reusability: React promotes the creation of reusable UI components, which speeds up development and makes applications easier to maintain. The “write once, use it anywhere” principle applies to React components.
Reasons to Learn React JS highlighted in the sources:
- Component-based architecture for building dynamic and efficient applications.
- Virtual DOM for faster UI updates and improved performance.
- Increased job opportunities: There is a high demand for React JS developers globally, with a significant increase in job openings.
- Attractive pay scale: React developers generally command competitive salaries.
- Easy migration: React facilitates migration from other technologies and older versions of React with features like deprecation warnings and codemod scripts.
- Reusability of code: Components can be reused across the application, reducing development time and effort.
- One-way data binding: Makes code more stable and easier to debug.
- Flexibility: React can be integrated with other libraries and frameworks and is suitable for large and complex web development projects.
- Strong Community Support: Being an open-source library, React has a large and active community, providing extensive documentation, resources, and support through platforms like GitHub and Stack Overflow.
- Testability: React views can be treated as functions of the state, making applications easier to test and debug.
Prerequisites for learning React JS:
- HTML: Standard markup language for creating web pages.
- CSS: Technology for styling web pages.
- JavaScript: Lightweight, interpreted programming language for adding interactivity to web pages. Familiarity with ES6 (ECMAScript 2015) standards, including its syntax and features, is also important.
- npm (Node Package Manager): Default package manager for Node.js, used for managing JavaScript packages and modules.
- Code Editors/IDEs: Platforms like Sublime Text, Atom, and Visual Studio Code for writing React code.
- Basic understanding of the DOM (Document Object Model).
React Architecture:
React is often described as the “V” (View) in the MVC (Model-View-Controller) architecture, although it’s more aligned with a component-based approach. For the “M” (Model) architecture, patterns like Flux and Redux are commonly used to enforce unidirectional data flow and manage application state. A React application is composed of a set of nested components, with data flowing through props and state.
Learning Curve:
React is considered to have a shallow learning curve compared to some other frameworks like Angular, making it suitable for beginners. The ES6 syntax is generally easier to manage, especially for smaller applications.
Community Support:
React has a strong and active community. It is one of the top-rated repositories on GitHub with a large number of stars and a vast ecosystem of libraries and tools. The official documentation is easily accessible, and platforms like Stack Overflow have a massive number of React JS related questions with accepted answers, indicating a highly responsive community.
Market Trends and Job Opportunities:
There is a significant demand for React JS developers in the job market. Numerous job opportunities are available across various platforms, and the demand has seen substantial growth in recent years. React developers’ salaries are generally attractive and depend on factors like experience, skills, and location. Top companies like Reddit, BBC, Netflix, Facebook, PayPal, Instagram, Uber Eats, Airbnb, and Twitter use React.
Testing in React:
Testing is a crucial aspect of React application development. React’s architecture and one-way data flow make applications highly testable. Unit testing, functional testing, and integration testing are important types of testing. Tools like Jest and Enzyme are popular for React testing.
Real-Time Projects:
The sources mention several real-time project ideas that can be built using React, including:
- E-commerce App
- Chat App
- Social Media App
- Video Sharing App
- URL Shortener
- Music Streaming App
These projects demonstrate the versatility of React in building various types of interactive web applications.
Becoming a React JS Developer:
The path to becoming a React JS developer involves learning the fundamental concepts, gaining hands-on experience through projects, and staying updated with the latest advancements. Engaging with the developer community and practicing for interviews are also important steps. Employers often look for skills in JavaScript, HTML, CSS, React core concepts (JSX, components, state, props, hooks), state management libraries (like Redux), build tools (like Babel, Webpack, npm), RESTful APIs, and version control systems (like Git).
In conclusion, React JS is a powerful and widely adopted JavaScript library for building modern web applications. Its component-based architecture, efficient rendering through the Virtual DOM, unidirectional data flow, and strong community support make it a valuable skill for front-end developers. The demand for React developers continues to grow, offering numerous career opportunities with competitive salaries.
React JS: Component-Based Architecture Explained
Let’s delve into the component-based architecture of React JS. As highlighted in the sources, this is a fundamental principle that makes React a popular and efficient library for building user interfaces.
What is Component-Based Architecture?
In React, the user interface (UI) is broken down into reusable, self-contained components. Think of it like building with Lego blocks, where each block (component) has its own structure and function, and they can be combined to create a larger structure (the application). Each component manages its own structure and behavior independently.
Key Characteristics of Components:
- Reusability: One of the primary benefits is that these components can be reused throughout the application and even in other projects. This “write once, use it anywhere” principle saves development time and effort.
- Self-Containment: Each component is self-contained, meaning it encapsulates its own logic (how it behaves) and its own view (how it looks). This makes it easier to manage and understand individual parts of the application without affecting others.
- Independent Functionality: Components can function independently. This allows developers to focus on building and styling one section of the application at a time without breaking other parts.
- Building Blocks: React applications are essentially trees of components, where smaller components are composed together to form larger ones. There is often a root component at the top, with child and sub-child components forming the rest of the UI hierarchy.
- Logic and View Separation: Component-based architecture enables the separation of logic and view. This makes the codebase more organized and easier to maintain.
How Components Work:
- Rendering: Each component has a render method that returns a React element, which describes what should appear on the screen. This often involves JSX, an HTML-like syntax that gets transformed into JavaScript.
- Data Flow: Components interact with each other through props (properties) and state.
- Props are like arguments passed to a function; they are read-only and flow downwards from parent to child components. They allow parent components to configure and control their child components.
- State is data that is managed within a component and can change over time, triggering re-renders of the component and its children. Only class components can have their own state.
- Composition: Complex UIs are built by composing smaller, simpler components together. Parent components can embed and manage child components.
Advantages of Component-Based Architecture:
- Faster Development: Reusability and independent functionality allow developers to build applications more quickly. Developers can focus on individual components without worrying about the entire codebase.
- Improved Organization: Breaking the UI into smaller, manageable pieces leads to a more organized codebase that is easier to understand, navigate, and maintain.
- Increased Reusability: As mentioned earlier, components can be reused across different parts of the application, reducing code duplication and development effort.
- Enhanced Performance: While the virtual DOM is the primary driver of performance, component-based architecture facilitates targeted updates. When a component’s state or props change, only that component and its relevant children need to be re-rendered.
- Easier Testing: Individual components can be tested in isolation, making it easier to write unit tests and ensuring the reliability of different parts of the application.
- Better Collaboration: Teams of developers can work on different components simultaneously without interfering with each other’s code.
In summary, the component-based architecture in React JS is a powerful paradigm that promotes reusability, maintainability, and efficiency in building dynamic user interfaces. By breaking down complex UIs into smaller, self-contained components, developers can create applications that are easier to develop, understand, test, and scale.
React’s Virtual DOM: Concepts and Advantages
Let’s discuss the Virtual DOM in React JS in detail, drawing on the information from the sources.
The Virtual DOM is a central concept in React that plays a crucial role in its efficiency and performance.
What is the Virtual DOM?
- The Virtual DOM is essentially a lightweight copy of the actual DOM (Document Object Model).
- You can think of it as a tree data structure of plain JavaScript objects.
- Like the actual DOM, a Virtual DOM is a node tree that lists the elements and their attributes and content as objects and their properties.
- React’s render function creates a node tree out of the React components.
The Problem it Solves:
- Direct DOM manipulation is slower compared to most JavaScript operations. Browsers have to perform several costly steps when the real DOM is updated, including parsing HTML, recalculating CSS, updating layout, and re-rendering the tree.
- Many JavaScript frameworks update the DOM more than necessary, leading to inefficient updates and performance issues. For instance, updating one item in a list might cause the entire list to be rebuilt.
How the Virtual DOM Works:
React utilizes a process called reconciliation to efficiently update the actual DOM. This process generally involves three main steps:
- Update in Virtual DOM: Whenever the underlying data in a React component changes (due to state or props updates), the entire UI is re-rendered in the Virtual DOM representation.
- Diffing Process: React then compares the new Virtual DOM with the previous snapshot of the Virtual DOM. It figures out the differences between the two versions, identifying which Virtual DOM objects have changed. This process of finding the differences is often referred to as “diffing”.
- Patching the Real DOM: Once React has identified the changes, it updates only the necessary parts of the real DOM to reflect those changes. This means instead of re-rendering the entire UI in the browser, React applies a “patch” containing only the modifications.
Analogy:
The process of using the Virtual DOM can be likened to editing a blueprint of a house (Virtual DOM) before making changes to the actual house (Real DOM). It’s faster to modify the blueprint than to physically move rooms. Once the blueprint is finalized, you then make only the necessary adjustments to the real structure.
Advantages of Using the Virtual DOM:
- Faster Rendering: By minimizing direct manipulation of the real DOM, React achieves faster rendering and improves application performance.
- Enhanced Performance: The Virtual DOM leads to better performance of React applications, especially for complex and dynamic UIs with frequent updates.
- Reduced Load Times: Faster rendering has a massive impact on reducing load times and quickly adapting performance based on user traffic.
- Improved User Experience: By ensuring faster and more efficient updates, the Virtual DOM contributes to a smoother and more responsive user experience.
- SEO Friendly: While not directly a benefit of the Virtual DOM, React’s ability to perform server-side rendering (SSR), often facilitated by the Virtual DOM concept, can improve SEO. SSR allows the initial rendering of React components on the server, sending a fully rendered HTML page to the browser, which search engines can easily crawl.
- Cross-Browser Compatibility: The Virtual DOM is not browser-specific and helps in abstracting away browser-specific DOM implementations, leading to more consistent behavior across different browsers.
- Lightweight: The Virtual DOM itself is lightweight as it’s just a set of JavaScript objects.
Virtual DOM vs. Real DOM (Source):
FeatureReal DOMVirtual DOMUpdate SpeedSlowerFasterDirect UpdatesDirectly updates HTMLCannot directly update HTML; updates the Virtual DOM firstElement UpdatesCreates a new DOM if an element updatesUpdates the JSX if an element updatesManipulationMore expensiveEasierMemory UsageCan lead to memory wastageResults in no memory wastageIn conclusion, the Virtual DOM is a key innovation in React that significantly optimizes UI updates by acting as an intermediary between the developer’s desired UI state and the browser’s rendering engine. This abstraction allows React to efficiently manage and apply changes to the real DOM, resulting in faster, more performant, and user-friendly web applications.
React State Management: Concepts and Techniques
Let’s discuss State Management in React JS, drawing on the information from the sources and our previous conversations about component-based architecture and the Virtual DOM.
What is State in React?
In React, state is a way for a component to hold and manage data that can change over time. It is essentially an object that determines a component’s rendering and behavior. Unlike props, which are passed down from parent components and are immutable within the receiving component, state is local to a component and is mutable.
- Components can have an initial state defined within their constructor using this.state.
- State can be updated over time in response to user interactions, network requests, or other events.
- When a component’s state changes, it triggers a re-rendering of the component and its child components, allowing the UI to reflect the updated data.
Stateful vs. Stateless Components:
- React components can be categorized as either stateful or stateless.
- Stateful components (class components) have the ability to maintain their own state and manage changes to it over time. They inherit from React.Component. As per ES6 standards, class components are the primary way to manage state.
- Stateless components (functional components), on the other hand, do not have their own state. They primarily receive data as props from their parent components and render UI based on those props. They are essentially pure JavaScript functions. However, with the introduction of React Hooks, functional components can now also manage state.
Updating State with setState():
- To update the state of a class component, you should always use the this.setState() method.
- setState() merges the new state with the old state. This means that if your state object has multiple properties, you only need to provide the properties that you want to update.
- It’s crucial not to modify the state directly (e.g., this.state.property = newValue) because React may not recognize the change and won’t re-render the component. Direct modification also prevents React from correctly managing state transitions.
- State updates through setState() may be asynchronous, meaning there’s no guarantee that the state will change immediately. React might batch multiple setState() calls into a single update for performance reasons. Therefore, when calculating the next state, you should not rely on the current values of this.props or this.state immediately after calling setState().
State and Component-Based Architecture:
- In a component-based architecture, state is often managed in parent components and then passed down to child components as props. This facilitates the flow of data through the application hierarchy.
- Child components can then trigger state updates in their parent components through callback functions that are also passed down as props.
Unidirectional Data Flow and Flux:
- React follows a unidirectional flow of data or one-way data binding. This means that data flows in a single direction throughout the application, which provides better control over the data.
- Flux is an architectural pattern introduced by Facebook for managing data flow in React applications. It emphasizes unidirectional data flow through four main components:
- Actions: Objects that represent events or changes that should occur in the application. They have a type field.
- Dispatcher: A central hub that receives actions and dispatches them to registered stores. There should be only one dispatcher per application.
- Stores: Containers for application state and logic. They register with the dispatcher and update their state based on received actions. When a store’s data changes, it emits a change event. Flux can have multiple stores.
- Views (React Components): Display data retrieved from stores and can initiate actions based on user interactions. Views subscribe to change events from the stores they depend on.
Redux:
- Redux is a popular open-source JavaScript library for managing application state, often used with React. It implements the principles of Flux but with some key differences.
- Key Principles of Redux:Single Source of Truth (Store): The entire application state is stored in a single store.
- State is Read-Only: The only way to change the state is by dispatching actions.
- Changes are Made with Pure Functions (Reducers): Reducers are pure functions that take the previous state and an action, and return a new state. They determine how the state should change based on the action type.
- Redux provides a more structured approach to state management, especially for complex applications.
React Hooks for State Management:
- Introduced in React 16.8, Hooks allow you to use state and other React features in functional components.
- useState is a fundamental Hook that enables functional components to have their own state variables. It returns an array with the current state value and a function to update it.
- useReducer is another Hook used for more complex state management, similar to how Redux manages state. It takes a reducer function and an initial state, and returns the current state and a dispatch function to trigger state updates.
Context API:
- The Context API is a React feature that provides a way to share values like themes, user authentication status, etc., between components without explicitly passing props through every level of the component tree (prop drilling).
- You can create a Context object using React.createContext() and then provide values to consuming components using a Context.Provider. Components can then access these values using the useContext Hook or a Context.Consumer.
State Management and the Virtual DOM:
- When the state of a component changes and a re-render occurs, React creates a new Virtual DOM tree.
- The diffing process then compares this new Virtual DOM with the previous one to identify the minimal changes needed to update the actual DOM.
- Efficient state management ensures that only the necessary components re-render when their relevant state changes, which optimizes the performance benefits of the Virtual DOM. Techniques like state collocation (keeping state close to where it’s needed) can further enhance performance by reducing unnecessary re-renders.
In summary, state management in React is a critical aspect of building dynamic and interactive user interfaces. React provides built-in mechanisms like the state property and the setState() method in class components, and Hooks like useState and useReducer in functional components. For more complex applications, state management libraries like Redux, or the Context API for global data sharing, offer more structured solutions while still leveraging React’s component-based architecture and the efficiency of the Virtual DOM.
React Router Navigation in Single-Page Applications
Let’s delve into React Router navigation, drawing upon the information from the sources, particularly sections of “01.pdf”.
What is React Router?
React Router is a powerful standard library system built on top of React. It is used to create routing in React applications. Its primary purpose is to enable navigation among different views or components in a single-page web application (SPA). Without React Router, displaying multiple views and updating the browser URL accordingly in an SPA would be challenging. React Router keeps the browser URL in sync with the data being displayed on the web page.
Key Components of React Router:
React Router provides several essential components that facilitate navigation:
- BrowserRouter (or aliased as Router): This is a router implementation that utilizes the HTML5 history API (pushState, replaceState, and popState events) to keep the UI synchronized with the URL. It’s the parent component that typically wraps your application and makes the routing functionality available to its descendants. In the provided example, BrowserRouter is imported and aliased as router: import { BrowserRouter as router, Route, Link, Switch } from ‘react-router-dom’;.
- Route: This component is conditionally shown. It renders a specific user interface (component) when its path prop matches the current URL. The exact prop can be used to ensure that the route only matches when the path exactly matches the URL. For instance, <Route exact path=”/” component={Home} /> will only render the Home component when the URL is exactly /.
- Link: This component is used to create links to different routes within your application. It functions similarly to the HTML <a> tag but prevents a full page reload, providing a smoother navigation experience in an SPA. The to prop of the Link component specifies the path to navigate to. For example, <Link to=”/about”>About Us</Link> creates a link that, when clicked, will update the URL to /about and potentially render the component associated with that route.
- Switch: This component is used to render only the first Route that matches the current URL, rather than rendering all matching routes. This is useful when you have multiple routes that might partially match the same URL, and you want only the most specific one to be rendered. All Route components are typically wrapped inside a Switch component.
How Navigation Works with React Router:
- You wrap your application’s main component with a router component like BrowserRouter.
- You define different routes using the <Route> component, associating a specific path with a React component that should be rendered when that path is matched.
- You use the <Link> component to create navigational links within your application. When a <Link> is clicked, React Router intercepts the click event and updates the browser URL without causing a full page reload.
- The router then compares the updated URL with the defined routes.
- If a match is found, the component associated with that Route is rendered within the application. The <Switch> component ensures that only the first matching route is rendered.
Types of React Routers:
React Router provides different types of routers to suit various needs:
- BrowserRouter: Recommended for most web applications. It uses the HTML5 history API for clean URLs (e.g., /about).
- HashRouter: Uses the hash portion of the URL (e.g., /#/about). It’s often used for supporting legacy browsers or when you don’t have control over the server configuration to handle regular URL routing.
- MemoryRouter: Keeps the URL changes in memory, not in the browser’s address bar. It’s useful for testing and non-browser environments like React Native.
Advantages of Using React Router:
- Provides a synchronous URL in the browser with the data displayed on the web page.
- Maintains a standard structure and behavior for navigation within the application.
- Essential for developing single-page web applications where content updates dynamically without full page reloads.
- Enables navigation among views of various components in a React application.
- Allows changing the browser URL and keeps the UI in sync with the URL.
- Uses the <Link> component for internal navigation, similar to the HTML <a> tag but without page reloads.
- The Switch component helps in rendering only one matching route.
- It’s not necessary to manually set the browser history.
In the example provided, a basic navigation structure is implemented using BrowserRouter (aliased as router), <Link> components for “Home”, “About Us”, and “Contact Us”, and <Route> components within a <Switch> to render the corresponding components (Home, About, Contact) when their respective paths are matched. This demonstrates the fundamental principles of React Router navigation in action.
The Original Text
hello everyone and welcome to this comprehensive full course on react GS react GS is a popular JavaScript library developed by Facebook for building Dynamic and interactive user interfaces it is widely used for creating single page applications where seamless performance and efficient UI updates are crucial so known for its component based architecture reactjs allows Developers to build reusable UI elements making development faster and more organized so whether you are a beginner stepping into web development or an experienced developer looking to expand your skills reactjs is an essential tool in today’s web ecosystem known for its flexibility and efficiency reactjs Powers some of the most dynamic and interactive web applications today so in this course we will guide you through the fundamentals of react GS its key features and the skills required to become a proficient react GS developer with that said let’s outline the agenda for this react GS full course so first we will start by exploring introduction to react GS where we will understand what react GS is what its purpose and why it’s widely used in modern web development next we will dive into reasons to learn reactjs where we will discover why reactjs is valuable skill and how it can boost your career followed by the features and prerequisites and then we will will explore aspects and advantages of react GS where we will understand the unique benefits that react GS brings to web development moving on we will cover reactjs fundamentals to learn about components jsx and The Core Concepts that form the foundation of reactjs next we will discuss conditional rendering in react GS in this section we will understand how to render content conditional based on different states after that we will dive into react components and react life cycle where we will explore component structures and life cycle methods for better app control then we will move on to react router where we will learn how to manage navigation and routing in react applications next we will explore react hooks understand the power of hooks for managing State and side effects we will continue with reactjs Redux to master State Management in react application using RS next we will compare react versus react n to explore the key differences between react Gus for web and react native for mobile development then react versus angular where we will understand how react GS Compares with angular in terms of performance and structure then we will move on to react GS projects where we will get hands-on experience with practical reactjs projects next we will explore testing in react in this section we will learn how to write and run effective test for your react applications and finally we will conclude with how to become a reactjs developer to discover the road map skills and resources you need to Kickstart your career as a reactjs developer followed by the react GS interview questions where we will prepare for frequently Asked interview questions to boost your confidence and secure job opportunities but before we begin please like share and subscribe to our YouTube channel and hit the Bell icon to stay updated on the latest content from edu Rea also edu rea’s reactjs training course equips you with the skills needed for professional web development roles focusing on improving uiux using this powerful JavaScript library this course covers key react fundamentals including jsx props State events reducers actions and the state tree master these Concepts to build modern web applications confidently so check out the course and enroll today also check out edureka’s full stack development course with certification this course is designed to take you from the basics to Advanced web development covering everything from HTML CSS and JavaScript to powerful Frameworks like react nodejs and express along with API integration and MySQL for database management so check out the course Link in the description box below now let’s get started with our first topic that is Introduction to reactjs Let’s dive into the three major reasons to make react so useful so the first one is component based architecture in react component based AR architecture UI is broken down into reusable self-contained components each component has its own structure and behavior in this layout the page is divided into different parts a navigation bar at top a side bar at right and the main display area in react we build each of these sections as individual components meaning each one can function independently so the next one is virtual Dom the virtual Dom is essentially a lightweight copy of actual Dom instead of directly making changes to the real dor every time something updates react Updates this virtual dor First Once react has figured out what has changed it then updates only the necessary parts of the real Dom and after that we have the development speed react component structure allows us to quickly build into small parts of the app individually since each component is separate we can focus on building and styling one section at a time without breaking other parts of the page this saves the time and help us to build application faster so in short react component structure development speed and virtual Dom help us to create Dynamic efficient and userfriendly applications so now let us move on to what is react first of all react is a open- source JavaScript library react is maintained by developers worldwide and is focused on building user interfaces making it highly adaptable and Community Driven the next one is react makes develop vment fast scalable and simple react component based architecture allows developers to break uis into reusable Parts speeding up the development and making the large application easier to manage next is react is used for building user interfaces mainly single page applications react is perfect for single page applications where content updates dynamically without reloading the entire page offering a smooth user experience and the last one is rea react enables data changes without reloading the page with features like virtual Dom react efficiently updates the data in real time allowing the web applications to respond quickly without full page reloads now let us have a look on trending Frameworks so here is the data from stack Overflow and here we can see that reactjs is most trending framework currently so react is the popular choice for developers nowadays now that we have a clear understanding of of what react actually is let us explore why it is a such popular choice among the developers so the first one is virtual dor reacts virtual nor updates changes efficiently without refreshing the whole page making apps fast and responsive the second one is development speed with the reusable components and large community of pre-build libraries react helps developers to build applications quickly next one is stability RAC uses oneway data flow which means change in child component won’t affect the parent component this keeps the app stable and easy to manage the next one is interactive interface react makes it easy to build highly interactive uis which means user can get smoother and more engaging experience the next one is component based architecture react divides the uis into components allowing us to build update and use part independently saving a lot of time and effort the next one is server site rendering rea supports serers side rendering which can improve page load speed and SEO by rendering the content on the server before sending it to the user the next one is simple to use reapp Simple syntax and clear structure make it beginner friendly letting new developers start creating apps quickly the next one is flexible development react flexibility allows it to be used in a variety of projects from small apps to large scale Enterprise applications so now that we have covered the key components of rea let’s move on to setting up your development environment where we are going to download vs code and then we will install nodejs for running react on our systems now to download visual studio code we need to visit the official website of Visual Studio code we are just going to click on this website and then we are going to just click on the download if you’re using Windows you just need to click here in case you’re using Mac you need to click here so I’m using Windows I need to click here so now after the download process you’ll see something like this you just need to click on I accept the agreement next just check these boxes create desktop icon open with code and open with code click on next and finally click on install so that will install Visual Studio code into your system so now after installing vs code into our system we are going to install nodejs and to download nodejs just visit this website nodejs.org and you just need to click on this download the LTS version so now after clicking on the download node GS LTS version you’ll be able to download the exe file so after completing the download process you will see this interface you just need to click on next and I already have node installed in my PC so I’m getting these options otherwise you’ll just get a next option let us say I want to change it and then again you will click on next next and and then you will just get a finish option here so that will start the installation of nodejs so after successfully installing the nodejs what we are going to do is we are going to open our Command Prompt to cross check whether nodejs has been successfully installed into our system or not so for that we need to write one command so the first command is node hyphen V so this right here is telling the version of our nodejs so the next command is npm hyphen V so this is also telling the version npm version that we have installed so by this we know that not GS and npm has been successfully installed into our terminal so what is the next step so next step is to open our vs code and then in vs code we are going to check whether node and npm are working or not so here I am on my visual studio code so I’m going to open my terminal here and here is my terminal so inside terminal I’m going to repeat the commands so the first one was node V that’s it it is showing the version of node and it is successfully working in my visual studio code and then it is npm V so now npm is also working in my visual studio code so now we have successfully installed the vs code and nodejs into our system and now we are ready to create one project so now that react is installed let’s move on to creating our first react app so to create our first react app we are going to open Visual Studio code inside this we are going to open one folder so here I’m going to create one new folder and I’m going to name it as react Dev we’ll just select this folder and now we have access to this folder inside this folder we are going to open the terminal and inside the terminal we are going to create the app so to create the app we are going to use this command that is npx create react app and after this you can provide any name which you want to provide to your app let’s say I’ll provide it as react and then enter and the installation of the dependences will start just write y here and enter so now this will create the react app and add the dependences into my react tab so we need to choose the different project name I’ll just choose npx create react app and let’s say counter that’s it now it should create my project and now this is installing the packages into my folder right here we can see the counter app has been created and the package.json has been added inside it now let us wait till the react app is getting created now here we can see that our first react app has been successfully created the node modules has been added the source components has been added and we can see the package Json and everything is added in our folder so this is how you create your react app and now what we are going to do is we are going to run our react app so for that we can just use CD and the app name that is counter and enter and after this we’ll just start our reaction tab that’s it we are going to launch our react tab so here we can see this is our first react app so by default when you are going to install the react app you are going to see these things so now we are going to make some changes in our react app and then we are going to write the code for hello world so there are some useless files that you need to delete first so inside the SRC you are just going to keep the index.js and app.js rest you can delete and that’s it I’m going to remove the logo also now we are going to make some changes in our app.js so first of all we are going to remove these and then we are going to remove the code inside the return statement and we are going to write one heading here that will be hello world that’s it we are going to save it and we’ll move on to index.js inside index.js first of all we’ll remove all this and then we are going to [Music] remove this and this so now we have going to just save our file and just look at the output so this is the output the code we have written inside the return statement is hello world so this is our first react app we have successfully written our first code in react that is hello world so now what we are going to do is we are going to learn some coree concepts of react and then we will be creating one counter app so now that our first react app is up and running let’s dive into the Core Concepts of react that make building application so powerful and efficient so the core components of react includes components components are the building blocks of react tab each part of your UI is component which can be reused to make development faster and cleaner they help us to break down the complex uis into manageable pieces next on we have jsx jsx is a syntax that looks like HTML but works inside the JavaScript it makes it easier to write the structure of your react component j6 allows you to combine HTML like code with JavaScript functionality in one place next on we have is virtual Dom the virtual Dom is lightweight copy of the actual Dom react uses it to update the UI efficiently by only changing what’s necessary making the app faster this reduces unnecessary operations and improves the performance next on we have a state management state refers to the data that changes in your app react lets you to manage State inside the components so when the state changes your UI automatically Updates this is essential for handling Dynamic data like form inputs or user interactions next on we have props props is basically short for properties these are used to pass data from one component to another helping you make your component Dynamic and reusable they allow you to customize component based on the data that they receive next on we have is event handlers event handlers in react are functions that handles user interactions like click form submissions and more allowing your app to respond to user actions they provide a way to trigger changes in your app based on the user input so now that we have covered the code concepts of react let’s switch to vs code and apply these Concepts in real project we will see how everything works together with Hands-On coding so the first thing again I’m going to do is I’m going to open one folder inside my visual studio code so I’ll just create one more folder naming naming counter I’ll just select this folder and again we are going to create this app so inside our terminal again we are going to write npx create react app counter that’s it so our app has been created now what we are going to do is we are going to move into the app by CD counter that’s it now again we are going to delete the unnecessary things that includes index. CSS logo and these two files we are also going to delete this app. CSS so now we are going to create one more file inside it which will be counter dogs that’s it we are going to work on these three files and again one more file we should create for our styling so it should be style. CSS and that’s it so first of all we will start with counter do GS so by creating this counter. GS we are going to understand the concepts of State props and event handling so what we are going to create is we are going to create an app in which we will increment or decrement the numbers and by creating that we will be understanding the concepts of State Management and properties and event handling so first of all we are going to import the react to use the GSX syntax and Define the react component so it will be import react from react now here we are defining the properties that we are going to use which includes count increment and decrement and along with that one reset so these are the properties that we are passing so basically counter is a functional component that takes the four props which includes count increment decrement and reset these props are passed down from the app component enabling counter to display and manipulate the count value based on the user interaction now the counter component returns GSX that renders diff element with class counter inside this div section the current count value is displayed inside H1 element as a counter count and then we have created these three buttons including increment decrement and reset the increment button triggers the increment function from the properties to increase the count when clicked and after that we have this decrement button so this triggers the decrement function from the properties to decrease the count when clicked and then on we have this reset button this reset button triggers the reset function from the properties to reset the count to zero when clicked now here we can see that each of the button uses onclick attribute to call the function when clicked since increment decrement and reset functions are passed as props from the app component clicking these buttons triggers the respective functions in the app that we are going to write so for example the increment button is clicked the increment is called which increases the count in the app component State this triggers a rerender of counter updating the displayed count so that’s it for the counter. JS and now we are going to create the app.js now here we are on the app.js section so let us have a look on the app.js so for imports we are importing use state from react this hook manages state within the component and after that comes the counter so counter component from counter that we have created this child component will display the counter and the button from the user interaction now again we are importing this style. CSS from the Style app that we have created after this comes the app components so inside the app component UST state zero initializes account State variable with the initial value of zero and after that count holds the current count and set count is a function that updates the value so state in react is persistent across renders meaning count will retain the value until it’s updated by set count and after that comes the event handlers these functions are used to update the count State based on the user actions first of all we have the increment so it increases the count by five each time it is called by executing set count count plus five and then on we have is decrement a decreases the count by one each time it is called and then we have this reset so reset sets count back to zero by calling the set count zero so by defining these functions the component becomes interactive allowing user to modify the state and see the changes reflected in the real time so that’s it for the app.js we’ll just save this file we’ll just save the counter. JS and after that let us move on to the style. CSS so after writing counter. JS app.js and we are just going to keep the index.js as it is we have just excluded the codes those were not necessary so we have already seen those in the first counter app that we created for hello world so now we’ll just save the index.js and for styling. CSS first of all we have just styled the body using the font family display justify content alignment of items height and the background color after that we have styled the app using these styling techniques and then we have styled the counter after that we have styled the button and that’s it we have made the button hover so that’s it for the styling now we have created the counter app here we learned about three concepts the properties the state and the event listeners so these are the three core components that we have learned and now we’ll just save this project and we’ll run our project so here is the counter app that we have created so when we are clicking on increment the count is incrementing by five when we are clicking on decrement it is decrementing by one and after clicking the reset button it is being reset to zero so this is the simple app that we have created using props States and event listeners so now that we have a proper idea about prop State and event listeners we’ll now move on further and we’ll just create our Mario game so before that as we have now understanding about the prop State and event listener so basically what are components so all the files that you can see inside the source are components of the real so app.js is one component counter. GS is one component index.js is one company so again the other core concept of react was GSX so this right here the code that we are able to see is basically jsx syntax so basically this is a JavaScript code but we have written HTML inside the Javascript file so this is called GSX so now we have clarity about the Core Concepts of react first of all the components here are the components then the GSX these are the GSX and after that we have properties these are the properties and then these are the event handlers and we have also seen the State Management so after that we have this styling so that’s it about the increment project and I hope you are clear with the concept of prop St and event handlers so now that we have clear understanding of the concepts of react we’ll be starting our Mario game so let us now understand how we created this Mario game using react so first of all we’ll start with the sources in this there is a section named esset in this we have included the audio font and the images that we are going to use so after this we are going on the section of components so in inside this components we have one section that is atoms in this we have included all the components that are being used in this game for example we are using Birds bricks clouds key message obstacle sun and all so after this we have this molecules in this we have included the footer the loading screen Mario the corrector and the mobile controls again we have included the title and the score so now one by one we are going to have a look on this codes so first of all let us start with birds so inside Birds there is a section of bird dogs so first of all we are importing the use effect and the use state from the react and after that we are importing the bird. CSS from the stylesheet file so first of all here is ready is a piece of state that starts as a false it will later be said to True when the document is fully loaded and after this the use effect hook runs after the component mounts it defines a function set load that sets is ready to true so after that this part checks if the document is ready to fully load it if it is it calls the set load immediately if not it adds the event listener for the load event which will call set load once the page finishes loading the cleanup function removes the event listener if the component unmounts or if the effect runs again at last we have the return statement the component return a diff containing another diff for the birds the class name of the inner diff changes based on the is ready state if is ready is true it adds the class bird animate which likely triggers an animation so that’s it about the bird. GS now let us look at the bird. CSS so for that first of all we have provided this GF and then we have included the background repeat as no repeat background size height right width position top and left then we have provided the bird animation and after that we have provided the key frames and media queries so that we are already familiar with what are key frames and media queries so now after bird. JS we have bricks. Js so again in bricks. JS the component Imports the use effect and use state from react to handle the state and a life cycle events so it also Imports the CSS file . CSS to style the components and after that we have this const is ready so here is ready is a piece of state initialized to false the state will eventually determine whether the animation of the brick is active or not after that we have is use effect the use effect hook runs when the component mounts it defines the function set load that sets is ready to true and after that we have this LL statement this part checks if the document is fully loaded and if it is document. ready state is complete it immediately calls set load if the document is not loaded yet it adds an event listener for the load event which will call set load once the page finishes loading the cleanup function removes the event listener if the component unmounts or if the effect runs again and after that we have this return statement the component returns are div with a class bricks container inside it there is another diff for the bricks the class name of this inner diff changes based on the is ready state if is ready is true it adds a class brick animate which likely triggers the animation so after this brick. JS we move on to brick. CSS so again in brick. CSS we have given this background image and The Styling that we have included is background repeat background size height width position bottom and lift next on we have brick animate these are the animation that we have provided and after that the key frames and the media queries so now after birds and Bricks let us move on to the clouds so again in cloud. Gs we have included all these functions just like brick. JS and cloud. JS so you can just pause this and go through the code again it is basically the same function we are just importing the cloud. CSS and we have changed this return statement so after this again we have cloud. CSS we have included the background image background repeat background size height width position top and left again we have included the Cloud’s animation and key frames and media queries you can just pause this video and go through the code once and if you have any doubt you can just comment in the comment section after that we have this key message JS inside this key. JS for first we have imported the key message. CSS for The Styling so inside this we have basically created one press container and we have given two paragraphs including Enter key and space key so here Enter key is for starting the game and space key is for jump so after that we have included obstacles so now let us look at the obstacle dogs code so inside this obstacle. JS first of all the component Imports the CSS styling images for the obstacle and necessary hooks from the react it also Imports Redux Hook from the state management so after that dis patch is used to send actions to the Redux store is playay and speed are selected from the Redux state where is playay indicates if the game is running and the speed represents the current speed of the game so now after that we have this use effect that sets up the interval that runs every 100 milliseconds it dispatches action to update the redu store from the current dimensions and positions of the both obstacles by accessing their boundaries rectangles through the Rifts each property height left top width are getting updated from the both obstacle so after that we have one more use effect so this use effect runs whenever the speed value changes if the speed is non- negative it sets the time out to adjust the speed to the small value after 1 second this could be used to ensure that the game continue to run smoothly so after that we have this return statement the component returns a container of the obstacles each obstacle is represented as a image this class name changes based on the isplay state adding moments classes if the game is active the style props adjust the animation duration based on the speed making the animation faster or slower depending upon the game’s current speed so that’s it about the obstacle dogs now we’ll move on to the obstacle. CSS so here we have provided some basic styling techniques to obstacle container obstacle 1 2 and then we have separately styled the obstacle one and two and then obstacle one move then obstacle two move then we have provided some key frames and media queries so again if you have any doubt you can just comment down in the comment section and rest you can pause the video and look at the code so after this all we are left with the Sun so we are importing the sun. CSS for The Styling and we have included one class container Sun container and then we have given the class name as Sun so again inside the CSS we have provided the background image of the sun which is a gif form and then we have provided The Styling that includes background repeat background size height width position top and right and again we have included some media queries into it so that’s it about the atom section now we’ll move on to the molecules so inside molecules what we have done we have created footer loading screen Mario the corrector score and the title so now we’ll just quickly look to the every molecule so before moving on to the molecules we have just imported everything that we have created Birds bricks clouds key messages obstacles and Sun so before moving on to the molecules here we have imported all of these things so each Line Imports the component of specific file path for example bird component is imported from the birds file the imported components are presumbly react components that will be used in the application to render the different parts of the UI and after that this line exports all the imported components into single object by doing this it allows other modules to import any of these components easily from one Central File instead of importing each of them individually from their respective files so now first of all let us look at the Mario character development so here the component Imports style images or the Mario character audio files for jump death sound and various hooks from the react and reds so after that this used dispatch hook allows dispatching actions to the redex store several State values are selected from the redex store to manage the game State such as whether Mario is dead the game is loading or the Mario’s position and the Dimensions now after that these selectors retrieve the position and dimension of two obstacles allowing for the Collision detection now after that we have this audio handling for this we are using use memo hook to create audio objects for jump die and background music this ensure that these objects are only created once optimizing the performance now after that this handle key function listens for the key presses if the enter key is pressed the G is isn’t playing it dispatches an action to set the game as ready and if the space key is pressed while Mario is not jumping that triggers the jump and plays the jump sound after 400 milliseconds it stops the jump sound and resets its playback time so after this right here you can just pause and have a look at the code 1 by one and if you have any doubt you can just comment in the comment section below so after this we have again used this use effect that mon the Mario’s position and checks the collision with the both obstacle so now if the Collision is detected it dispatches the action to set Mario as dead and plays the dead sound it also repeats the game score after the short delay so that’s it about the Mario character and you can just go through the code line by line this code just shows the use of use effect and how we are controlling the Mario and when the Collision is happening to change the state of the Mario and everything so now let us quickly look at the CSS of Mario so here for Mario we have given the styling technique which includes width height position bottom and left then we have animated the jump and then we have added the key frame and then we have added the animation if Mario dies and key frame again for that and we have added some media queries so now after the Mario character development let us quickly look at the footer section so this component Imports the CSS file for styling which would typically Define how the footer looks and after that this defines the functional component named footer functional components are simpler way to create the components in the react and after that we have this return statement inside this div it displays the text copyright followed by the current year which is dynamically obtained from the new date get full year this ensures that the copyright year is always up to the date without the manual change it also includes the anchor tag that links the placeholder the target blank attribute makes the link open in the new tab and then R adds the security feature to prevent the new page from the accessing the previous ones and that’s it for the footer section now this line basically exports the footer component as a default export of the module making it available for import in the other files so that’s it for the fooo section JS now this is the pH section CSS we have just styled the copyright button and the copyright link so now after the foter design let us look at the loading screen so inside the loading screen first of all we have added the import statements this Imports necessary hooks use effect and use state from the react the Mario character image CSS for styling and Redux function set loading screen and use dispatch so now after this we have added this this basically declares the functional component named as loading screen so now after that we have used is ready so is ready is the state variable initialized to false if it will set to True after the specified delay indicating that the loading is complete so again dispatch is a function from Redux that allows the component to dispatch actions to the store and after that we have use the use effect this use effect runs once when the component mounts due to the empty dependency array it sets the timer for 5 seconds after which it updates is ready to True indicating the loading is completed and then at last we have the return statement the component renders a div with the class loading screen container it displays the Mario character image using the image tag while is ready is false it shows an H1 element with the text loading once is ready is true it displays the enter button when the button is clicked it dispatches the set loading screen false action likely to update the global Redux state to hide the loading screen and then at last we have this export default loading screen so that’s it for the loading screen now let us look at the CSS of the loading screen so inside the loading screen CSS we have provided width height position top left bottom right background color color display Flex Direction justify content alignment of items Gap and Z index then we have styled the Mario loading then the loading title and then the enter button after that we have provided this hover effect to the enter button so that’s it you can go through the code line by line and again that is it for the loading screen so now let us move on to the mobile controls again we have added the Imports here and after that we have added this mobile controls this defines the functional component that is named as mobile controls and after after that we have added this is play Mario jump is die so this indicates if the game is currently being played Mario jump indicates whether the Mario is currently jumping is die indicates if the game is over and dispatch is used to send the action to the Redux store after that we have used use memo to create an audio object for the jump sound this ensures that the audio is only created once for the performance efficiency and after that this function is triggered when the start button is clicked it checks if the game is not already playing and if it is not over if the both conditions are met it dispatches an action to set the game to ready and after that we have created this function this function is called when the jump button is clicked it checks if the Mario is not already jumping and if he isn’t it dispatches an action to set him as jumping plays the jump sound after 400 milliseconds it stops the sound and resets the playback time and at last we have this return statement so in this the component renders the div with the class mobile controls container it conditionally renders the start button when the game is not playing or not over again the over button when the game is over the jump button when the game is playing and at last again we have this export statement and now again we have the styling of mobile controls so here is the media query and then the mobile controls container and after that we have styled the start button jump button and control button again we have styled these button by applying the filters and we have given the background color and then we have given the background color to the control jump button so that’s it for the CSS of mobile controls and the JS off mobile controls you can go through the code line by line and again comment down if there is any doubt now at last we’ll move on to the calculation of the score so now we are at the score. JS again we have added the import statements that Imports the necessary hooks from react Redux function and CSS file so after that we have this declaration this defines the functional component named as score and after that we have used this query selectors for score last score play die and dispatch so the score shows the current score from the RCT store and the last score shows the last score recorded and the play is basically a Boolean indicating if the game is currently being played die is basically a Boolean indicating if the game is over and dispatch is a function that is used to dispatch the action of the Redux store and after that we have included this high score this basically initializes the state variable high score it retrieves the high score from local storage passing it as an integer or defaults to zero if the high score is not found so after that we have used this use effect this use effect runs whenever the dependencies change that means incrementing the score if the game is being played or not over it sets the time out to increment the score by one to every milliseconds and then updating the last score and the high score and after that we have the return statement so this component basically renders the div with the class score container if the game is currently being played it displays the current score if the game is over it displays the last score it always displays the high score along with that and at last we again have the export statement so that’s it for the score. GS and we’ll move on to the score. CSS so for score. CSS we have just applied these styling techniques including the media query and the styling of high score so after that last one we have is title so inside this title. JS first of all the component Imports the CSS file for styling ensuring that the component has desired looks so again after that we have this cons title this basically defines the functional component named as title and after that we have this return statement so the component Returns the div with a class name title container which acts as a wrapper for the title elements inside this div an image element displays the Mario logo it uses the imported Mario image as a source and it has the class Mario logo for styling and H1 element contains the text Mario jump styled with the class title this serves as the main title of the game and again we have the export default title so here is the styling so first of all here we have styled the container then we have styled the Mario logo then title and then we have added the media queries so that’s it for the title now let us quickly go through this index.js file so here each Line Imports the specific component from the corresponding directories so footer displays the copyright information loading screen shows the loading animation and enter button Mario represents the character and mobile controls provide the button for the mobile users score displays the current last and the high score title basically displays the game title and after that this line of code exports all the imported components as named export this means that when importing from this module elsewhere you can access each component by its name so again in the other index .js file we have exported the atoms and the molecules so that’s it we have covered all the atoms and the molecules that we have made for the Mario game so now what we are going to do is we are going to run our project so for running our project we are just going to add the command and then we’ll be able to run our project so here we are going to add the command to run our project so we are just going to write that’s it we are going to give the command as npm start and it will start our project so here is our game here is the output of our Mario game it is the landing page we can just click on enter and it is basically the screen here we have the enter key we have to press the enter key to start the game and then we have to press the space key to jump here we calculate the score the high score we have added these GIS deps of birds clouds sun and the bricks and here we have the Mario character so here is the footer basically we have designed the copyright and this is the title so this is the whole project that we have created using the react so I’ll just quickly enter key and now I can see the game has been started so again I can jump using the space key and my score is being calculated here my current score and the high is being calculated here so this is the final project that we have created using [Music] react starting with the first reason to learn react which is react is easy to learn most developers love react because it is efficient declarative and flexible what is even more important and exciting is that learning react is easier than learning other JavaScript Frameworks if we compare react with angular on learning basis react is a library and a complete solution that is built around one main concept which is to give you more freedom in how you use the library to compose and organize your own component based architecture while angular in turn is more like Constructor or a tree of components so you need to understand how its elements behave work and combine together nevertheless react’s relative Simplicity does not not purely depend on its file structure and component model but also making the code easier to understand and launch of course react doesn’t burden developers with too many things to be mentally Managed IT generally does have a simpler file tree and flexible component model but also that’s a significant benefit react tends to have a substantially shorter dependency list while angular’s dependencies from a dising set that’s problematic to track react aims to make develop life easier by considerably shortening the equivalent lists the more difficult a technology is to learn the longer it takes to start the development process therefore a steep learning curve is one of the main reasons why react has gained so much traction in such a short time given react Simplicity businesses today are more inclined to use it thus building their projects faster now moving towards the second reason to learn react that is increased job opportunities there are thousands of jobs in the world which demand react GS skills there are more than 43,000 jobs available on LinkedIn alone in India for react as compared to 2019 there has been 184% of increase in the openings for rad GS developers in the year 2020 according to India Today a quest report States after cid9 reactjs developer is one of the top digital skilled jobs in demand this quite a huge number of job opportunities makes react one of the skills most of the application developers want to learn and secure a good job third reason to learn react could be attractive pay scale of course salary is important today react has the best pay scale on most of the job suggesting websites like LinkedIn glass door Etc talking about the salary Trends in India the current average salary for roles of react domain is 735 5K which includes the average salary of 597k for frontend developer or engineer the average salary of 654k for software engineer and the average salary of 1 million for senior software engineer now this could be a major reason to learn react because money actually matters in professional career the next reason to learn react is easy migration most of the communities that were not aware of reactjs are now migrating to the reactjs as it is very easy to understand and Implement they have started rewriting the code on react some top companies like Reddit BBC Netflix Facebook as PayPal instacart Uber Eats Airbnb Twitter OK Cupid Netflix Etc are using react this increases the job requirement of react skills in the world a lot of successful and big organizations dare to migrate on react because react provides the facilities which help in Migra ation easily as mentioned in react documentation when react deprecates a pattern they study its internal usage at Facebook and add deprecation warnings which let them assess the impact of the change sometimes they back out if they see that it is too early and they need to think more strategically about getting the code bases to the point where people are ready for the change if they are confident that the change is not too disruptive and the migration strategy is viable for all cases they release a deprecation warning to the open-source Community they are closely in touch with many users of react outside of Facebook and they monitor popular open-source projects and guide them in fixing those deprecations given the sheare size of the Facebook react code base successful internal migration is often a good indicator that other companies won’t have problems either nevertheless sometimes people point out additional use cases they haven’t thought of and they add Escape hatches for them or rethink their approach react not only cares for the migration from other technology but also from older version of react itself to the newer version of react they don’t deprecate anything without a good reason they recognize that sometimes deprecations warnings cause frustration but they add them because deprecations clean up the road for the improvements and new features that they and many people in the community consider valuable for example a warning about unknown Dom props in react 15.2.2 was added many projects were affected by this however fixing this warning is important so that they can introduce the support for custom attributes to react there is a reason like this behind every deprecation that react adds when they add a deprecation warning they keep it for the rest of the current major version and change the behavior in the next major version if there is a lot of repe manual work involved they release a Cod Mod script that automates most of the changes code mods enable us to move forward without stagnation in a massive code base and they encourage you to use them as well so that’s how react helps in migration the next reason to learn react is reusability which is a boon for developers react doesn’t require big lines of quotes to program an application in react we say that everything is a component a user writes small codes called components and combines them to form another component simply any app made with react is a tree of components react follows write ones use it anywhere principle for example if we are building an Instagram app using react Jus we will have many components like a separate component for navigation another one for the story section also for news feed then for profile and all other section of the application components are basically like functions the word has seen a big jump in the increment of the number of developers switching to react JS for which reusability of code plays a vital role moving to sixth reason to learn react which is data binding data binding is the process of synchronizing data between the model and view there are two basic implementations of data binding one directional and twood directional react uses oneway data binding which doesn’t allow child elements to affect the parent elements when they are updated this makes code more stable and easier to debug this also makes the code predictable and ultimately improves the performance of the application if we compare react data binding approach with any other JavaScript framework let’s take angular angular uses two-way data binding to connect the Dom values to the model data this makes it simpler to work with but also has a negative impact on performance it makes it slower when the application deals with lots of data requests it also makes debugging difficult and results in less predictability another reason why you should use react is its flexibility that manifests itself in a number of ways flexibility is especially visible when it comes to the use of react for web development web development projects tend to grow into bulky systems that may be difficult to fix or enhance first when we talk about reacts flexibility we refer to the libraries innate modularity as we know reacts architecture allows bundling front-end code into custom components this providing a solid foundation for the overall development process optimization the react’s position on the scale of opness is a stable the library neither locks nor guides you into their way of doing things on the one hand it dictates how you should create reusable components on the other hand it gives a free hand to decide how to handle routing and testing our organized dependencies and more this degree of Freedom can turn out confusing for newcomers initially but with time working in a react development environment becomes a pure delight for developers this way react allows you to write clean modular code breaking the project into separate components as a result when code is modular it gets easy to maintain and scale second react is super flexible in the sense that it can be integrated with other third party libraries and MVC Frameworks you can choose to create a react project from scratch or gradually introduce react to your existing literacy code base creating a new react app is not too difficult embedding react components one by one into your code written using other Technologies is not a problem as well and vice versa it’s really relatively easy to integrate third party libraries into react applications so using react for front end is a great choice besides while we are on the topic of flexibility it should be noted that another significant advantage in the ease of transfer and support of react native apps react native is actually a framework for building native apps using react so if you know how to develop applications using react you are already well on your way to getting well worsed in react n to they are conceptually similar most of the react Concepts transfer to react native thus you can waste no time learn react native and start developing mobile applications for IOS and Android with a native look and feel if we compare react and angular on this as I have discussed just now react gives us the freedom to choose the tools architecture and libraries for developing an application on the other hand angular offers a limited amount of freedom and flexibility now let’s see the E reason to learn react that is fast rendering react is a client side JavaScript library that uses server side rendering why is it a benefit enhanced support for serers side rendering tones react into a robust performance oriented solution for creating content focused applications be it a web application or native rendered applications for Android and iOS react has everything for a brilliant performance faster rendering has massive impact on reducing load times and quickly adapting the performance in real time based on user traffic flow it’s common knowledge that the faster the page load is speed the more users won’t leave the website and will use your service or purchase your product this is crucial for online business and after covid-19 online businesses have seen a new Milestone react’s virtual Dom is basically the prime cause of faster rendering and better performance of react apps first of all the react virtual Dom that is virtual document object model can be understood as a tree data structure of plain JavaScript objects accordingly react’s advantage over other Frameworks is that it creates virtual Dom as a copy of the real Dom and whenever the state change in a react component happens it reenders the virtual Dom first compares the old version to the new one and eventually only the required minimum is changed in the real Dom instead of re-rendering the entire UI reacts virtual Dom serves as a layer between how things are supposed to look and the actual processes happening to render all of these things onto the page now let’s move to the ninth reason to learn react that is easy debugging when something goes wrong it is important that we have breadcrumbs to trace the mistake to its source in the code base in react props and state are those breadcrumbs if you see something wrong on the screen you can open react da tools find the component responsible for rendering and then see if the props and state are correct if they are you know that the problem is in the component render function or some function that is called by render function the problem is isolated if the state is wrong you know that the problem is caused by one of the set State function calls in this file this two is relatively simple to locate and fix because usually there are only a few set State function calls in a single file if the props are wrong you can Traverse the tree up in the inspector looking for the component that first Poison the Well by passing bad props down this ability to trace any UI to the data that produced it in the form of current props and state is very important to react it is an explicit design goal that state is not trapped in closures and combinators and is available to react directly while the UI is dynamic we believe that synchronous render functions of props and state turn debugging from Guess work into a finite procedure we would like to preserve this constraint and react even though it makes some use cases like complex animations harder react results in not only easily debuggable code but also highly testable applications react itself makes it easier to create a clean architecture that is friendly to testing if you are working with react we don’t have to do any extra configuration of UI tests instead we can use justest that is basically Facebook’s JavaScript test Runner that is configured right out of the box and works seamlessly with reactjs applications if we choose to develop a new application using Create react app just will go with it by default so we will be able to execute tests rapidly just as a node based Runner therefore while testing a reactjs application a developer can run unit tests in a node environment not in real browser by mocking components under test traditional UI test execution tends to be slow but with react UI tests are run quite faster UI tests often end up being brittle however by separately testing single react components in a node environment we can avoid flakiness and ensure test results reliability this is because in such a way we will be in the position I to test pure functions which unlike with traditional endtoend UI tests is much less time consuming both in terms of writing and maintenance if we are running unit tests using react we can be sure that it won’t be a big challenge to write these tests quickly and update them easily now here strong documentation and community support for react becomes the final 10th reason to learn react being an open-source Library reactjs has what it takes to keep attracting more and more newcomers to its Community which makes it stronger over time the feeling of belonging to a community is a solid base that a software developer can rely on when learning new technology or working on a complex project as react developer you will definitely get this feeling the react library has once gotten into the growth Loop and seems to intend to remain there as long as possible as of today reactjs is one of the five top rated repositories on GitHub with over 170k stars and over 5 million applications publicly admitting to using it react has a rich ecosystem to benefit from or contribute to besides finding one’s way around all this information won’t be a big challenge as the react documentation can be easily found on the official website the community is active so you can get rapid feedback or response to your inquiry once you feel stuck currently on stack Overflow there are over 14 million questions tagged react JS that have at least one accepted answer that’s incredible how responsive the community is so once you encounter a problem chances are someone has already had the same problem and there is a solution to it so that you will only have to copy paste it from the corresponding discussion thread with this I have covered top 10 reasons to Lear nonreact last but not the least I want to say traditionally open-source projects get along without full-time developers and are being improved through the work of independent contributors who are committed to the project to a certain degree but reacts contributors commitment is much deeper than that which has a direct positive impact on react developers coding [Music] experience Js X jsx stands for JavaScript XML it’s an XML or HTML like syntax used by react it extends the ecma script so that XML and HTML like text can coexist along with JavaScript react code this syntax is used by the pre-processors like Babel to transform HTML like text found in JavaScript files into standard JavaScript objects with jsx we can go a step further by again embedding the HTML code inside the JavaScript this makes HTML codes easy to understand and boosts javascript’s performance while making our application robust a virtual dor like an actual dor a virtual dor is also a note tree that lists the elements and their attributes and content as objects and their properties react’s render function creates a not tree out of the react components it then Updates this tree in response to the mutations in data model caused by various actions done either by the user or by the system itself the virtual Dom basically Works in three steps first whenever any of the underlying data changes the entire UI is rendered in the virtual Dom representation then the difference between the previous domor representation and the new one is calculated once the calculations are completed the real Dom will be updated with only those changes that have actually been made you can think of this as a patch in a virtual dorm the changes are applied only to those Elements which have actually changed or updated this will not just make our application faster but also there is no memory vage testability react views can be used as functions of the state here state is basically an object which determines how a component will render and behave thus we can easily manipulate with the state of the components which we pass to The reactjs View and take a look at the output and triggered actions events functions Etc this makes react applications quite easy to test and debug server side rendering or SSR server side rendering allows you to pre-render the initial state of your react components at the server side itself with SSR the server’s response to the browser becomes only the HTML of the page which is now ready to be rendered thus the browser can now start rendering without having to wait for all the Java script to be loaded and executed as a result the web page loads faster here the user will be able to see the web page in spite of react still downloading the JavaScript creating the virtual domor linking events Etc at the back end oneway data binding unlike other Frameworks reactjs follows the unidirectional data flow or one-way data binding A major advantage of one-way data binding is that throughout the application the data flows in a single single Direction which gives you better control over it because of this application state is contained in specific stores and as a result rest of the components remain Loosely coupled this makes our application more flexible leading to increased efficiency Simplicity the use of jsx files makes the application really simple easy to code and understand as well even though you can use plain JavaScript over here using jsx is much easier react’s component based approach along with the distinct lifestyle methods also makes it very much simple to learn so that was about the features of react okay so now that you’ve understood the features of react let’s move on and take a look at the prerequisites that are required in order to learn react the first and foremost prerequisite is HTML HTML stands for hypertext markup language and it is the standard markup language for creating web pages and web applications a markup language is a computer language that is used to apply layout and formatting conventions to a text document markup languages make the text more interactive and dynamic it can also turn text into images tables links Etc the next prerequisite that you will need to know is CSS CSS basically stands for cascading style sheets CSS is a technology that is proposed and developed by the worldwide Web Consortium or the w3c for short it was released to help free web developers from the tedious process of inline styling and make styling a separate entity in itself next up is Javascript JavaScript is a lightweight interpreted programming language with objectoriented capabilities that allows you to build interactivity into otherwise static HTML Pages the general purpose core of this language has been embedded in Netscape Internet Explorer and almost all of the web
browsers following JavaScript is npm npm stands for node packet manager it is the default packet manager of node.js that is completely written in JavaScript it was developed by ISAC zutter it was released in 2010 and since then it is responsible for managing all the nodejs packages and modules npm is the world’s largest software registry which is completely free and open- sourced developers all over the world make use of npm for sharing software code editors or Ides code editors and Ides are integrated development environments are platforms where programmers write their code and produce their final products some examples are Sublime Text atom Visual Studio code Etc so basically if you want to write your react code you will need to make use of any of the code editors or IDs okay so now moving on towards the next topic which is the react architecture as mentioned earlier react is the v in the MVC architecture the M or model architecture is provided by flux plux is an architectural pattern that enforces a unidirectional data flow it controls derived data and enables the communication between multiple components using a central store which has authority over all the data any update in data throughout the application must occur here itself plux provides stability to the application and reduces time errors so now let’s take a look at some of the important Concepts in react the first thing that you should be aware of is components in reactjs everything is a component if you guys remember I’ve already given the one Lego House application example earlier on in this session just like the Lego blocks are combined together to make a single structure components and react are integrated together to build one bigger and dynamic application so therefore in react the entire application can be modeled as a set of independent components these components basically serve different purposes components also enable us to keep the logic and the view separate in react multiple components are rendered simultaneously State and props state is the heart of react components they are basically the source of data and must be kept as simple as possible basically states are the objects which determine the component rendering and behavior they are mutable and can create Dynamic and interactive components States in react are accessed via this state function states also have something called as state life cycle so basically we need to initialize resources to components according to the requirements this is called as mounting in react it is critical to clear these resources taken by components whenever they are destroyed this is done in order to manage the performance and is called as unmounting in react it is not essential to use State life cycle methods but you can use them if you wish to control the complete resource allocation and retrieval process props props is the Shand for properties in react they are readon components that must be kept Pure or immutable props are always passed down from the parent to the child components throughout the application so therefore all the user needs to do is change the parent component State while the changes are passed down to the child component through props on the other hand a child component can never send a prop back to the parent component this helps in maintaining the unidirectional data flow and is generally used to render the dynamically generated data keys keys in react provide identity to components keys are the means by which react identifies components uniquely while working with individual components we do not require key as react takes care of key assignment according to their rendering order however we need a strategy to differentiate between thousands of elements in a list so this is where Keys come into picture if we need to access the last component in a list using keys it saves us from traversing the entire list sequentially Keys Also Serve to keep a track of which items have been manipulated they should be given elements inside the array to give elements a stable identity debugging in react now there will be a point when a developer goes through a roadblock it could be as simple as a missing bucket or as tricky as segmentation Falls in any case the earlier the exception is caught the Lesser is the cost overhead react uses compile time debugging and detects errors at an early stage this ensures that errors don’t silently turn up at the run time Facebook’s unidirectional data flow allows clean and smooth debugging fewer stack traces lesser clutter and an organized flux architecture for bigger applications event handling and manipulation of State whenever an event such as a button click or a mouseover occurs we need to handle these events and perform the appropriate actions this is done using event handlers so those were some of the important concepts of react that you should know when you’re learning react so now talking about the learning curve of react react unlike angular has a shallow learning curve and it is very much suitable for beginners the es6 syntax is easier to manage especially for smaller to-do applications in react you code in the JavaScript Bay giving you the freedom to choose your tool depending upon your need on the other hand angular expects you to learn one additional tool that is typescript which can be viewed as the angular way of doing things in angular you need to learn the entire framework if you’re just building a simple UI application now let’s move on so once you’re done with learning the basic concepts of react you’ll have to adopt the project-oriented learning approach this is because whenever you create a project you will have a 360° learning this is because when you create a project you will have to do everything by yourself therefore you’ll make use of all the programming Concepts resulting in better understanding and implementation remember that you do not have to master the world in your first project itself so start off by choosing a very simple one complete it by yourself and try your best not to copy anything from anywhere else as you proceed you can take a bigger applications and work on them it is sure that you will face difficulties while making your applications however it comes with a reward of learning if you are stuck at some point in your project try to break down your problem into minor parts and then work on each of them one at a time now once you’ve decided to learn react remember that you’re not alone there are a number of developer communities that will help you along the road in this session I’m going to be discussing about GitHub stack Overflow and edura Community GitHub as many of you would be aware of is the world’s leading software platform that brings together developers from all over the world it allows you to build your programs share your work or discover what you are looking for you can also engage with other programmers by asking them your doubts Etc stack overflow stack Overflow is another open community that entertains anyone who wants to code it will provide you with some of the best answers for even the most trickiest questions and errors and will also help you share your knowledge with others using stack Overflow not to forget if you have any doubts or queries regarding any of the Technologies you guys can also check out the edura community website and get all your queries answered by experts also make a note that a key to remember what you learn is to share so make sure you share what you learn with others last but not the least stay updated technology sees New Heights every day the version that you learn today will get modified in the upcoming days so make sure you keep yourself updated with all the latest react versions and update your projects [Music] accordingly now aspects of react JS there are three important aspects of reactjs we will talk about first is the virtual domor second is the data binding and third is the server s side rendering but before that if I talk about the architecture of a reactjs application any reactjs application is composed of a set of components so it includes n number of components and the inputs to these components are the properties which are referred to as props and estate and this complete architecture of components props and estate we will be talking about in the later slides so let’s talk about what are the different aspects of react chairs now there are few things you should know in advance before you start playing around with react so if you have never used JavaScript or the Dom at all before for example so I will suggest that please get familiar with those Concepts before trying to tackle or play around with reactjs so if I say what are the prerequisites to play around with reactjs so you should have familiarity with HTML and CSS you should have basic knowledge of JavaScript and programming you should have basic understanding of Dom Dom stands for document object model then you should have familiarity with es6 standards which we talked about so you have to know ESX syntax semantics and features and then finally you have to know what is nodejs and how npm is installed globally so these are some of the prerequisites I talked about to start with reactjs so let’s talk about virtual Dom now this is the first aspect we want to know about reactjs so let’s talk about the problem first what is the problem so Dam manipulation is the heart of modern interactive app but unfortunately it is also a lot slower than most JavaScript operation so when you write in JavaScript document. getet element by ID this is the ID of the element do inner HTML equal to some value now what happens actually behind the scenes what happens is that browser need to pass this HTML it removes the child element updates the Dom value with the new value then there is a complete recalculation of the CSS for the parent and child for the complete tree and then the layout gets updated so that is each element exact coordinate on the screen and then finally there is a complete traversal of the tree or the render tree and then it gets displayed on the browser now what happens as you can see on the point number four this is very much heavy that is recalculating of the CSS and change layouts because they uses a complex algorithm they affect and finally they affect the performance of the application and as well as updating the Dom properties it’s very complex now here we are talking about only one range now let’s say suppose if you want to update the Dom document object model 10 times directly then all the above six steps which I have talked about they will run one by one and they will update the Dom algorithms which will take whole lot of time to update all the Dom values that is why we say that real Dom is always lower than the virtual Dom please remember virtual Dom is a aspect or you can say concept which is introduced by reactjs now this slowness of the application can be made worse by the fact that most JavaScript Frameworks update the Dom much more than they have to for example let’s say that you have a list that contains 10 items for example so you check off the first item now most of the JavaScript framework would rebuild the entire list that is the complete 10 list that’s 10 times more work than necessary so only one item is changed but the remaining nine gets rebuilt again and again exactly how they were before so rebuilding a list is no big deal to a web browser but modern websites can use huge amount of Dom manipulation inefficient updating has become now a serious problem so what happens when you try to update the Dom in react the reconation process so what happens is that the entire virtual Dom gets updated the virtual Dom gets compared to what it looked like before and now you have updated it so react figures out the difference or which objects have changed only those change objects get updated on the real Dom and then the changes on the real Dom they cause the screen to change so I can say that in react for every Dom object there is a corresponding virtual Dom object so like any actual Dom virtual Dom you can say it’s a note tree that lists the elements and their attributes and content as objects and their property to directly change what is there on the screen manipulating the Dom is a slow process but manipulating the virtual domor is a very fast process or you can say it’s much faster because nothing gets drawn on screen it’s just like a manipulating the virtual domor as editing a blueprint as opposed to moving the rooms in an actual house if you can see that on the screen in the given tree the red one are the ones which have been changed and they have only been patched to the real domor instead of the complete tree so that is the power of a real Dom you can say now the important thing that how does react uses virtual Dom it’s very important so as I said that in react every UI piece is a component and each component has a state so react follows the observable pattern and listens for State changes and whenever there is a change it has been updated in the virtual Dom which gets reflected to the real Dom so in summary what I can say that what happens when you try to update the Dom in react so what happens that the complete virtual Dom gets updated the virtual Dom gets compared to what it looked like before you updated it and then it reflects the changes on the real domor which causes the screen to change that is the concept of a virtual domor now let’s talk about another aspect of reactjs which is data binding so reactjs follows very important to learn that reactjs follows unidirectional flow of data or one-way data binding as comp comp to other Frameworks which supports two-way data binding so in reactjs throughout the application the data flows in a single Direction which gives us a better control over the application so as you can see here that data flows from view to action from action it flows to dispatcher on dispatcher multiple actions can work and from dispatcher it goes to a store so react apps are organized as a series of nested components these components are functional in nature that is they receive information through arguments now if I talk about this oneway data binding or unidirectional data flow so flux I want to talk about little bit about here that flux is a new kind of architecture that Facebook uses when it works with react flux is more of a pattern than a framework and it has four main components you can see on the screen the one component is dispatcher now what dispatcher is doing that it receiving the actions and and it broadcast its payloads to the registered callbacks or to the store the second one is the store so a store is acting like a container for application State and Logic the real work in the application is done in the store the store you can say is registered to listen into the actions of the dispatcher and it will work accordingly and it will update the view so if I talk about view or more specifically the controller views so react comp components they grab the state from the store they grab the state from the store and then they pass it to pass it down to the child components so that is how data binding Works in reactjs it’s a oneway data binding or you can say unidirectional data flow now another concept of reactjs that is server side rendering so let’s talk about server side rendering now so server side rendering allows you to pre-render the initial state of your react components at the server side only so server side rendering which is also called as SSR in abbreviated form it is called SSR it is the you can say ability of a JavaScript application to render on the server rather than on the browser this is the exact definition of server side rendering I repeat this definition serers side rendering is the ability of a JavaScript application to render on the server rather than in the browser now there could be a question in your mind that why would you be ever want to do so so now I will list down some of the advantages that why you want to do so because it allows your site to have a faster page load time which is the key to a good user experience it helps in the SEO that is search engine optimization because what will happen that without server site rendering all your server ships is an HTML page with no body so just some script tags that are then used by the browser to render the application so in nutshell what is the difference between client side rendering and server side rendering so in client side rendering your browser downloads a minimal HTML page it renders the JavaScript and fills the content into it this is client side rendering and what is server side rendering on the other hand serers side rendering it renders the react components on the server and what is the output the output is the HTML content so that is the use of server side rendering so we talked about three important aspects of reactjs that is virtual Dom data binding and server side rendering now let’s talk about virtual Dom in detail so if I talk about virtual Dom as you can see on the screen that model gives data to view which in turn creates a Dom for it so here a model so model had information for the user ID and location it has been given this data has been given to the view which in turn has created the Dom the model gives data to the view which in turns create the Dom but you can see over here that if I change the user if I change the user from Len to Max that is the only change which has happened in terms of three properties as compared to three property only one property has been changed and that property only be reflected on the real domor that is the power of a virtual dor so as I talked about that what is a virtual domor right so virtual dor only give updates to the real Dom it not only gives the updates so that the complete page or the complete HTML or css does not get loaded again and again on the screen so now here see if location is changed if location is changed okay if I talk about the previous location the previous location was us it was compared and then you can see in the real Dom the location is changed to UK because virtual Dom it has not put heavy load on The View and makes our processing also very much faster so with reactjs when model gives data to the view if the Dom is empty react will create a Dom for it that is also a beauty or you can say advantage of a virtual Dom now as you can see here that with reactjs when model has given the data to The View and if the Dom is empty react will create a Dom for it but at the same time it is checking with the previous values and if it has found previous value is Ln and the new value is Max the user property has been changed to Max in the real term so let’s talk about the advantages of reactjs now what are the various advantages of reactjs the first one application performance is increased so which means that the creating the dynamic web applications now it has become very easier and reactjs is very much easier to learn now how the application performance is increased we have already talked about that it uses a concept called virtual Dom so enhancement of performance has been done or you can say application performance is increased because of the concept of virtual Dom it is used on the client side as well as on the server side reactjs can be used both on client side and server side and it also known to be a SEO friendly you can say library readability is improved this is one of the greatest advantage of reactj is that the readability of the code or the readability of the application has been improved a lot another is that it can be easily integrated or used with other Frameworks like angularjs or meteor or VI JS even with knockoutjs or emberjs another advantages of reactjs I want to talk about here is that the reusable components so reactjs focuses on the concept of reusability so react UI as we know that it is declared inside the components so if I talk about a component here at this stage so component is like a function that accepts the props as inputs and outputs the declared interface the U should be composed of as many as components as possible to maximize the reusability so the concept says that you should decompose into multiple components your reactjs application at the same time reactjs is a very much famous Library so there are very much great developer tools available out there for you can say Chrome and Firefox there are browser extensions for react available in Chrome and Firefox browsers so these extensions you can say allows you to inspect the react component hierarchies in the virtual Dom so you can select individual components and examine and edit their current properties and state so these are some of the advantages of reactjs reactjs is very much popular nowadays and is used by almost all the developers across the globe now applications of reactjs so there are uh these famous applications which are using reactjs in their uh application or maybe browser application and some are using in their mobile apps so some are also using react native instead of react along with the reactjs in fact so some of the famous applications one of them is obviously Facebook Yahoo Uber Netflix Twitter Instagram Dropbox and New York Times so these are some of the very big or famous applications which are using reactjs or react native in their website or in their mobile mile [Music] apps so first of all we have the jsx so we have under jsx now there are multiple components under rat that makes the entire infrastructure as flexible as possible so like we have jsx then we have riat components then we have props then we have States life cycle events references key and then we have available rout so the are multiple references that we have that we are going to discuss now the core important component first of all is components so let’s discuss on the component on the structure for components first so components are what if you have web page so if you want to update different content if you want to handle different content you can say section separately then instead of refreshing the entire page what we can do we can declare we can add different sections at as different components so that we can Define different Logic for different sections we can have different separate views and then we can render multiple components in the same page where it can all have their own separate Behavior defined right so first of all we have components so components as we discussed in application can be modeled as a set of independent components and different components are used to serve different purposes this enables us to keep a logic and view separate so react renders multiple components simultaneously and components can be either stateful or it can be stateless so before we start creating components we need to include a few import statements so we have to define the import Rea and then only we can import start importing the components and then we can Define the individual functionality for these different components one by one for example here we have this one declared as component we can have the left side bar declared as a component and so on so everything in reat is a component and each component returns a Dom object it spills the entire UI into independent reusable pieces each independent piece is processed separately and it can refer other components in output and it can be further split into smaller components so valid re component accepts a single props object argument to produce a react element and these are called functional as they literally are JavaScript functions so here we can define a button where we can define a prop as on click and then we can link this to any of the other components suppose if this if you talk about the simplest way of defining a component is through JavaScript where we can Define function and then we can Define the entire components and components can Rea can be in two different forms it can be stateful or it can be stateless it can be stateful or it can be States now stateful remembers everything again we can it has its own memory where State doesn’t remember anything it does so as soon as the entire statements are executed it simply clears out this entire memory so core which stores information about components in memory and it can change change States it contains knowledge of past current and possible future State changes it receives information from the stateless components if State change is required it calculates States internal we can say internal state of components and it never changes the state contains no knowledge of past current and possible future State changes and it provides a referential transparency that is for some for same input it will produce same output as well as a part of stateless components then we have props so Props are read only components so whether components are declared as functions or class it must never change a change its props such components are called Pure functions so all component must act like pure functions with respect to the props as what we are going to Define all right now for example let’s say if we want to create any component here we want to define the props as well then we can create a components and then we can create separate props for example if you want to create a component in react then here it’s always advisable to go to source and under Source we can create a separate folder so here we can find folder name as components and then under components we can create the component file for example here we can create a component file as suppose C mp1 suppose here we have suppose header header. JS so if we have one component defined as header. JS we can Define header. JS and first of all we have to when we creating component we can import the react Dom element we we can Define react Tom from react Dom element that we have to that from in which this is currently present so we can Define react Tom then we can declare a simple constant where we can Define con con Conant such as my component we can write any component here suppose here we can Define my component now here we can make use of a simple Lambda function now in here we can create a function we where we can Define okay we want to return and then what exactly we are looking to return here we can Define that those parameters let’s suppose here we want to return as simple S2 as we have I can say component example we can define a simple component example here we can close the H2 element and then we can now once once we have closed it we can close the statements that we have currently opened up and then we can use react dom. render so that this particular my component that we have created this can be rendered this entire component can be rendered here and then we can Define okay in which so here we are going to use document get element by ID and suppose here we want to render this where we want render this in the root ID that we Define in index oral so in in ID we have defined as root let’s change the same thing under index as well so here we can Define this to be root right so here we Define the entire root element here and then once we add we can close IND statements so we can save this and now if you want to include this back in our own statement then we can easily do that right so here we can simply Define our own application we can Define the own index whever and however we want this to be vendored and then for creating a props so Props as we know all that in simple am terms if you say props is basically a shorthand for the properties so react uses props to pass attributes from parent components to child components and props are the argument based to the function or component which is ultimately processed by react so here we can Define multiple properties for it and then we can have it rended depending upon what kind of property we are going to create here so for example here instead of using the return statement here let’s do one thing let’s see here we create a simple function so here we can Define function so okay let’s return the statement here not a problem so after this we can create a simple function let’s create a function here by the name of app so here we can define a function for app and in here we can specify return now under return we can define suppose here we want to return a division and then under division for example we have multiple message that we want to save here so here we can Define message as username for example here we are going to save multiple username then here we can Define message as suppose we have John here we have again another message that means another usern that we want to Define here suppose here we have SEL and here we have another message this can be multiple components we can save suppose here we have mik this can be multiple username that we are going to Simply render here and then when we when we are rendering the element here we can Define the in function right so now instead of Define the the even earlier instead of defining the entire my component we can Define the function and under function we can create a function for message that we have specified here so here we can Define message function and under message we are going to Define this as props with the properties that we have defined all right so here we can Define the entire properties as in how or well we want to render these as a part of the props and components and then we have other properties such as we have state so States basically allow us to create components that are Dynamic and interactive so state is basically private it must not be manipulated from the outside also it is important to know when to use state so it is generally used with data that is bounded to a change for example when we click our toggle button it changes from inactive to active state that you may have noticed and state is used only when needed and we have to to make sure that it is used in render property that we have refined in in our JS otherwise it won’t include in the state and we do not use state with static components the state can be all the state can only be set inside the Constructor alog together so we can include some code Snippets into see a small example so for example we can come back to our editor so let’s say here we can create a new file all together let’s say we name it as state 1. JS now here we can import react from react and then we can also work on importing react Dom from react now basically when we are working on the elements we have to make sure that we import the elements one by one so here we have to import react re Dom now here we can start now for the State Property let’s say here we can Define class for toggle where we want this to be extended not extend react. component that we have imported or we can also or now to work on this one here we also have to import Rea component as well so here we can also import uh if you want to import component then from the same re here we can Define the component as well if we looking to import multiple things and here we can Define react and component both from from the library where we have defined it all right so here we can define a simple class as sole as re component here we can Define us Constructor where we can specify a value for Constructor and then we can Define value such as here we can define a super where we can a super object for having the value and then we can use this dot state so here we can store the state value as this do state and here we can Define is toggle here we can Define is toggle on if it is now here we can Define the property to be true then we can Define this. handle click should be set to using this pointer this handle click dot bind so here we can bind this to the this point that we have selected so as a part of the state now here we can also if you want we can bind this a state here and then we can Define multiple States as in when this when this should be on when this should be off and then we can alter M multiple states by Define the state life cycle as well one by one so we can Define if state is again one then again how we have to switch different states from one state to the other that is something that we are going to look at as soon as we proceed further with the entire module step by step then we have life cycle so Rea provides various methods which notifies when certain stage of life cycle occurs called life cycle methods so these are spatial event handlers that called at various points in components life so code can be added to them to perform various task and they are invoked in a predictable order and entire life cycle is divided into four different phases we have the initial phase where we have get default props get initial State then we have component will Mount render and component did Mount then in the updation phase here we have have should component update component will update render and component did update then in the props change phase we have components will receive props should component update component will update render and component did update and then in impound simply is going to Define component with unmount so component is going to be unmounted after a specific value based on the condition whatever we have defined and events are basically triggered at reactions to specific actions like Mouse over Mouse click key press we can set any kind of event parameters and then we can Define it easily we can do that now as soon as any event is triggered this is going to Simply trigger the vat event and event passes the event arguments to the event handler so whenever any event is specified in GSX the synthetic event is generated and this synthetic event wraps up the browser native event and I pass as argument to the event handler that’s how it is structured and then we we have references so references stand for again and references are basically used to return references to a particular element or component returned by render so when we are rendering any element here then we can use references to specify a particular element now basically this is mostly used for managing Focus text selection or media playback and then we can also be used for triggering imperative animations or we can easily use this with third party Dom libraries as well we can do that these are the main features available in Rat and again we also have the component for rat router as well so reat router is basically a powerful routing Library built on top of reat framework so it helps in adding new screens and flows to the application very quickly so it keeps the entire URL in sync with data that is being displayed on the web browsers so in router we can have an easy understanding of the application views it can restore any state and view with simple URL it handles the entire nested views and resolutions States can be restored by the user by moving backward and forward it can help us in maintain a standardized structure and behavior while navigating it to the implicit CSS transitions we can easily do [Music] that what is conditional rendering in react J okay let’s see the definition in react you can create distinct component that encapsulate Behavior you need then you can render only some of them depending on the state of your application so when you are building some react applications we might often need to show or hide some HTML on some certain conditions right so in simple words what is conditional rendering conditional rendering is nothing but if a given statement is true then the if statement executes or else the L statement will execute so we have an example here for a better clarification now let’s imagine a person is appearing for an exam and the candidate must score 50% so this is the condition here so if the candidate scores 50% then only he will pass this exam or else he will fail so this might be considered as a simple real life conditionally rendering statement or an IFL statement and also I have an interesting fact here conditional rendering in react works the same way the conditions Works in JavaScript okay next we have different methods in rendering so let’s see what are all they first is IFL statement then element variables turn operators and finally short circuit operators let’s see each of it in a detail form here first we have IFL statement and IFL statement will execute the action contained in the if block when the condition is satisfied otherwise it will execute the actions contained in the else block so now let’s check this in a simple syntax and see here we have a condition which is to be evaluated and we have a statement inside the if block so this will execute when the condition there will satisfy or else the statement in the else block will be executed now let’s see this in a practical way now I am using visual studio code as a code editor okay now you can see I have have a user.js file opened here and we have app.js here I have included user here and also imported the user file here okay now let’s start coding now first and foremost we have a scenario here so let’s imagine there are two person one person from the edura team and another person is not a edura team person now now the person from edura if he sign in or if he log in to the this page and he must see a welcome page and if the non edura person signs in here he must see a please sign in page before he signs in so that is what we are going to design today with an simple IFL statement first and we will see the other conditionally rendered methods also so we will start coding here so first we will import react here I have the export default user so this helps me to import the user here so we have to Define it here for better practice now I have imported react here then I am declaring a class user extend react do component and also I am constructing a prop and I’m creating a super class and here I am giving the condition this dot St logged in false here I I’m giving false because the user will not be a member first then after he signs in he will become a member so I’m default keeping here as a false okay then I am rendering this const is logged in this state is log 10 okay here I am returning the condition and return the statement now I’m writing the else part return please sign in for happy learning in Ador yeah now here you can see as I have kept the state as false so default the react will work in local host 3000 so here you can see the output please sign in for happy learning Ura has I have kept this state as false now here I will give the styles for a visible changes you can see in the website so I am giving the Style part okay yeah this is image and I have given a simple Style part here so now if I keep the state as true then this welcome to edura page with an image should be executed so let’s see yeah you can see here welcome to edura with a Eda page image background and if I do false false then yeah you can see please sign in for happy learning in edor okay and also the thing is the IFL statement does not work inside the GSX because IFL statement is not a valid syntax inside the react JS now you might be thinking what is GSX GSX is Javascript XML it makes the code easier to write and add HTML into the react yes now let’s see what is element variables element variables are simple to approach to extract the conditional render into a function element variables are variables that holds jsx elements you can conditionally assign elements or components to these variables outside the jsx and only render the variables within jsx now we use JavaScript variables to store elements right so this will also Al help us conditionally render a entire component or only a part of component while the rest of the output does not change here so this is one of the benefit also it holds js6 element inside this so this is an advantage so let’s see the syntax here we have a variable and the same IFL statement with the variables assigned to the statements so let’s see here this variable is a memory for the values or it is the value will be stored in this variables and this is the same as the condition which is to be evaluated and we have a statement so this statement is assigned to this variable whether the condition is true then this statement will be executed to the user or else the else part will be executed to the user now we will see the Practical example in the visual studio code now you can see I’m editing in the same code I’m not changing anything here I’m just eliminating the F statement from here okay and now we have import and here we are using a variable so I’m using a variable button for that I have created a button here as a login button and a log out button here as well okay now I want to import this two buttons into my user.js file so let’s do that I will import log out button here and import login button okay now here these both are the child components of greetings so I want this greeting to be imported in user.js as well so let’s do that import greeting yeah now you can see right now I want this to be returned so I will return Dev greeting is loged in okay which is equals to okay this is the state F now we are using button right so I am declaring here the button okay now let’s write the main syntax let button then I’m writing if statement if is logged in button is equal to log out button on click so we are giving a event here that is on click this dot handle log out click okay now you might think where this handle came from I’ll explain now let’s give else part also copy pasting this but here log in okay we have here handle log out and login click so we have to give here also so we are giving this dot handle loging click is equal to this dot hand login click dot bind this okay so this is the event hand law dot bind this okay and also we have to give this state handle login this dot set state so I’m setting the state here as is logged in true okay now same thing for log out button false okay now this should work you can see a login button here which didn’t have previously for a statement and you can see the changes here now I am not a user of edura then I should get this page once I log in then I should get welcome back to edura page okay so this is what the element variable statement here I am assigning the values to this button if I click the button over there then the handle login click should give me true value and log out click should give me false value okay I hope you all understood the ifls and element variables next in our list is Turner operators let’s see the conditional tary operator is the only JavaScript operator that takes three operant this operator is frequently used as a shortcut for IFL statement okay now let’s see the syntax here we have a condition over here this is the condition is to be evaluated with a question mark So this question mark means if the condition is true or false if it is true then this statement will be executed if false then this statement will be executed so here the colon is the else part is the difference between true and false part now let’s check this also in terms of practical way this is the simple way of writing any conditional rendering here we have the same thing as the element variable here we have to just change the if and you can see here I’m giving the question mark here and I’m taking off this else I’m just assigning the column yeah with only this two changes here the code will be working I’m setting this to true for changing so you can see welcome back to eding with just three changes we are getting the same output here okay see log out so I’m getting this page if I log in I should get this page okay next we have a interesting operator that is short circuit operator short circuit evaluation is a technique used to ensure that there are no side effects during the valuation of the operant in an expression The Logical and operation helps you specify that an action should be taken only on one condition otherwise it would be ignored entirely here the approach is a specific case of this jary operator that we just learned now when we want to render something or nothing then we use short circuit operator now let us see the syntax yes this is the syntax now here the expression is first evaluated from the left hand side of the operant okay and if it is true then it is evaluated see the condition is to be evaluated and this is The Logical operator and this is the expression if the condition is true then this expression will be evaluated if the condition is false you will not get any kind of output here so this is the beauty of short circuit operator then we’ll see in the practical way here I have the same code just I have taken the buttons here I don’t want that button so here I am writing the syntax return this state logged in and and operation and I’m giving the style and welcome back to edor okay yes here we have the value as true so let’s check the output yeah welcome to edua and I will change here welcome back to Eda see we come back to Ed now if I change this to false so let’s see what see there is no output so that is what I mentioned you before if the condition is true then this output will be executed if false you will return nothing so this is the end of the conditional rendering now we will learn how to prevent component from rendering in rare case you might want a component to hide itself right even though it was rendered by another component to do this return null instead of its render output so returning null from a component renders method does not affect the firing of the component life cycle method so now I’m taking you through the online compiler I’m using GS pable this is a converter of the JavaScript now here we have a function called warning banner and we have props and I returning null here okay so we are writing a warning sign um let me change here I will write danger okay you can see the Visible Changes here itself danger okay here we have a phage extension and I’m giving this true here we have handle toggle click and I am giving has hide and show now if we click on hide so the message will be here hidden from rendering now I want to show this message then we can show here from returning null if we hide then you will not get any of the output here so this is also a kind of short circut operator and but here you will not get any of the side effects by giving the return as null now we’ll talk about components in detail so first thing first that in react everything is considered as a component so I will say in react everything is a component so on the screen you can see that there are multiple components 1 2 4 3 and five and on the web browser we need to add them just like components so they have been added just like a Widgets or sections or web parts or specifically components and all these components are integrated together in react to build one react application so in react what I can say is that components lets you split the UI into you can say independent reusable pieces of code and you can think about each piece in isolation and that is where the concept of reusability comes into picture that each component can be reusable at a later point of time but conceptually components are like JavaScript functions you can say like that they accept some arbitrary inputs so the inputs to a react component is called props and the return react elements describing what should appear on the screen we can easily update or change any of these components without disturbing the rest of the application so as you can see that if I want to update or change any of the feature of this component one I can update it without disturbing the rest of the application or you can say without disturbing the other components on my application now how components are split internally so single view of UI is divided into logical pieces so on the left you can see that it’s a single view or you can say react based application but how it is divided internally into logical pieces so the concept in of component in reactjs always says that you should have a parent component and then you can have child components or sub components and it behaves like a tree so at the top you will have parent component or you can say base component and then there will be some branches or some branches beneath it so the starting components becomes the root it’s called The Root component and the rest of all other becomes you can say the branches and the sub branches so in this diagram you can see the component one is the root of the UI tree two and three are the children of one and four and five are the Sub sub branches of the second component so that is how you can split the complete UI in reactjs components now each component returns one Dom element so as I mentioned that in every component you should have a render method and a return statement so each component in reactjs it returns one Dom element and how it is returned that there is a API called react Dom and it has a method called render so react dom. render will allows you to render the different components on your application so the jsx elements must be wrapped in an enclosing tag so always please remember that if you have to embed the jsx elements inside a return statement or a render method you have to wrap it in a enclosing tag so here I am creating a es6 standard component class component 3 so 1 2 2 4 and 53 is here which is written like this that hello world welcome to edura and react dom. render I am calling the component component one because component one is my root component and where I want to show you is the ID of that div element that is document. getet element by ID content now if I talk about props and state so react components are basically controlled either by props or you can say by state so we will talk about them now but before that what are just a summary of the components that everything in react is a component each component returns a Dom object as I mentioned that component divides your UI or splits your UI into independent reusable pieces and then each independent piece is processed separately a component can be divided into a root component and into the child components and then we can further split into smaller components compon now this is very important to understand that how you render a component so when react sees an element representing a user defined component it passes the GSS attributes to this component as a single object and those are called specifically props so you see here this is a function welcome which is just like a component having some props as a parameter so we call here react. render with the welcome name welcome name let’s say name is the prop over here having the value with and react calls this welcome component with the name vipul as the prop so this becomes name equal to vipul is the props welcome is a component which returns H1 tag and then react Dom efficiently updates the Dom to match this H1 tag that is how a component is rendered in reactjs now the other fundamental the most again a very important you can say fundamental of reactjs are the props now what are props so prop helps components to converse with each other or to communicate with each other this is I can compare it with you can say arguments or parameters of a function so if in this example class body extends react. component return header and footer now in header name equal to Bob and name equal to Alex so how can I return this property to this class component by using this do props do name so what this doprs do will return this doprs do name then it comes to header it will return Bob and this. props do name for the footer component it will return me Alex so how you can access props in reactjs if you want to access props in reactjs the syntax is this doprs do name so using props we can configure the components so now I have another header and footer components and I’m passing a different value name equal to Miller and name equal to CI so in the header component if I write this this doprs do name in the previous example also I wrote this doprs do name but the value was something different and in this case the footer component will return me this doprs do the value will be Cod so Props are basically used with components they revolve around the components they help in the conversation of different components via props we can do the conversation or communication between the different components in reactjs and how to access those props the props are accessed using this doprs do name or you can say this doprs do the attribute name or attribute value so if I talk about props they work similar to HTML attributes data flows from downwards from the parent component so as we are talking about a UI tree a parent child relationship so in terms of props it’s a unidirectional flow of data props are immutable that is they are pure here we are talking about pure functions or pure components so Props are immutable so as compared to which is mutable which we’ll talk later but props please remember are immutable so they are pure in nature they can set default props so we can set some default properties around the props now let’s talk about what is pure and impure here we are talking about so whether you declare a component as a function or a class so as we talked about components can be of two types a function component or a class component but it must never modify its own props so Props are always read only they are immutable in nature so it is very well said that all react component must act like pure function with respect to their props so let’s talk about what is this pure function and what is this impure function here we are talking about so for example there is a function called sum having parameters A and B and it is returning a plus b so in this particular example this is called a pure function why they are called Pure because they are not attempting to change the input values they will always return the same result for the same input so by that what I mean is that I’m not altering the value of a or b inside the function definition that’s why this is called a pure function but when I talk about a impure function because the function is impure so it changes its own input so for this particular function the input was account and amount and you can see there that I’m changing the value of account so it becomes a impure function and that is not allowed when it comes to components and props because all react component must act like pure function so Props are read only or you can say props are immutable in nature now components and props we talked about that there are two types of components you can create in reactjs because components allow you to split the UI into independent reusable pieces and you can think about each piece in isolation they are basically just like JavaScript functions but there are two types of components which you can create based on es5 or es6 is standard so if it comes to es5 is standard you can create a functional components but the recommended way and I will recommend that you always create a class component so how you will create a function component normally just like we create a function so function welcome having some props or the parameters but if you want to create a class component so you have to use the keyword class the component name which extends from react. component and it should have always have a render method and a return statement so that is the these two are the different types of components which we can create but from a react point of view they are always equivalent these two forms of component are always equivalent now another fundamental is state but before moving to the state or you can say another fundamental let’s get deep dive into some of the examples so that the three basic fundamentals which we talked about jsx components and props you can have better understanding about these okay so let’s get started so I’m just opening the nodejs command prompt so I have opened the prompt so I’m moving to the D drive and I’m moving to a specified location and then I’m am opening the code in a editor called Visual Studio code so let’s talk about the basic example that how you can render the jsx in react JS a very basic and simple example we will talk about that how you can render jsx in reactjs okay so what we have done over here is that we have a react Library the reference of a react Library okay and then reference of a react dom. library and then reference of The BJs in the script tag I have called reactdom do render and in that react dom. render because we want to render the jsx okay and please remember that you have to use script type equal to text Babel to indicate the jsx code in JavaScript of jQuery we refer script type equal to text/javascript but when we are working with jsx you have to use script type equal to text /b to indicate the jsx code and include b. min.js this is very important and this b. min.js this is a browser script tag in react dom. render in the H1 tag so please please remember that this render method takes two parameters always the first is your jsx element and another is your placeholder okay let’s move to the another demo where we will see that how we can use the JavaScript in jsx so as we know that we can also use JavaScript in jsx it takes the angle brackets as the beginning of the HTML syntax and cly Brees as the beginning of the JavaScript syntax okay so here you can see that I have created an array name equal to some names and in the react dom. render I using a JavaScript names on the names array I using the map method which is calling on the name and on the index key that is a key value payer and in this I’m returning the key equal to index hello and the name now you see here this name is represented in the cly bra as a attribute because names if I don’t put it in the C braces will be considered as a simple text so let me save this file and run this so you see here hello Lis hello Emil and hello Kate the reason being why this output because I have written here is hello and passing the parameter as a jsx so I’m using the JavaScript in the jsx and looping around the values in an array using the map function or map method which is inbuilt method of the array collection so that is why this particular output is shown hello Ellis hello Emil and hello Kate because these are the three values which are there in my array okay now let’s move to another example again a very simple one that I have created an array having the key values as 1 and two now in the react dom. render I am calling this array now what will happen that in my output it will represent that hello world react is awesome now in the next in this example what I’m doing is I’m I am defining a component so we talked about props we talked about jsx we talked about components right so in this particular example I’m defining a component so what is a Syntax for defining the component class then the component name which extends from react. component then it creates a component class and it implements a render method please remember that the class components or the function components always should have a render method class components always implements a render method to return a component instance of the class so if I talk about before version 16 of react chairs it uses react. create class to create a component class now it has been deprecated and we are using the es6 standard okay now components can have attribute and you can use this. props do some attribute to access them just like in this case I’m using this doprs do name so what what I’m doing is that in react dom. render as I mentioned you have to call the parent component or you can have to call the root element in this case there is a component called Hello message okay now in the Hello message component I am passing a prop with the attribute name let’s say equal to name and its value is John now what will happen in the Hello message it is returning hello this doprs do name as I mentioned while talking about the props that how you can access the prop okay how you can access the prop so how you can access the prop you can access the prop is this doprs do attribute name please remember how you can access it this do props do attribute name this is very important to understand and now let’s see the output of this I’m opening it in the browser it is showing me the output hello John okay now let’s talk about this doprs doch now what is the use of this doprs doch so react uses this doprs doch to access component children notes or you can say child notes so you can see here this doprs doch so please remember that the value of this. props doch it could have three possibilities in fact so if the component has no note then the value will be undefined then the second possibility could be that if can it can have a single child node let’s say an object and if multiple General nodes then it will become an array I repeat that there are three possibilities while using this doprs doch so component can have no children node then the value will be undefined in that case if it has single children node then it will be an object and if it has multiple children nodes then it will be an array so react gives us the utility called react. this is react. this is a utility given by by react for dealing with this doprs doch data structure so we could have used react. children. map to iterate into the childrens of the component without worrying its data type being undefined or object so what I’m doing over here is that I’ve created a notes list component that is a class component so class notes list extends react. component it implements a render method and it Returns the instance of this particular class since we are accessing the children of the particular component so we can use react. children. map in this I’m calling this. crops. children and it could have three possibilities but in this case since we have a children so our output would be hello world in this case the output will be hello world in a li structure so that is how you can use or you can access the children components also of a particular component let’s move to another example so types components can have specific attributes which are called props in react and can be of
any types it can be of any type so here you can say prop types. string. is required so what happens is that sometimes you need a way to validate the props so you don’t want users to have the freedom to input anything into your component so react has a solution for it and it is called prop type so what we are doing is that we are saying that prop types is of type string and it is required this is kind of a validation we are doing so what is done in this particular example is that the my title my title is a component has a props of title prop type tells react that the title is required it is required and its value should be of type string now if we give let’s say for example title a number value so where data equal to let’s say 1 2 3 for example okay then it will result in an error which means the props does not pass the validation and the console will show you an error message something like let’s say failed prop type so what I’m doing over here is my title I’m calling the component and there is a title where I’m passing the data and data is 1 to three okay so that is how you can Implement some kind of validations or you can apply some kind of rules where you don’t want to give the user a freedom to write anything in your component so the these are some of the basic examples we talked about for jsx for props and for components now let’s move to another set of examples so let me close this very quickly okay so these are again some of the small examples which allows you to work with jsx props and components but before starting this let me tell you one thing very quickly that as I told you that this is the nodejs website from where you can install the latest node.js version and once you install so there is a GitHub project provided by Microsoft open source project which is called create react tab so you have to write the command like this npm create npm install create react Tab and once you press the enter so a project will be created for you a complete react based project will be created for you which will allow you to have the complete solution structure in terms of index.js index.css app.js and app.css so you will have a SRC folder and a public folder so these two folders are very important and we will talk about this in detail so what happens once you create a Project based on create react App application a solution a builted solution is given to you which allows you to write the code or to test your different functionalities so it has two folders one is the public folder where we have a one HTML file called index.html where we have defined a root element in a div with the ID as root if I go to the source folder the starting file is the index.js in the index.js we have react. render now as you can see at the top that we have imported react we have imported react Dom imported the index from the solution structure now react dom. render calls the parent component which is the app app is the name of my parent component so if I go to app.js there is a parent component class app extends component you can either write component or you can also write react. component that’s not a problem at all every component as I mentioned should Implement a render method and there is a return statement which Returns the instance of that particular class now I can write the jsx inside the component in the return statement simple HTML and the JS structure the div I have given the div class name equal to app now there is a header in this header I have implemented a image with a class name app logo alt equal to logo and H1 equal to class name app title now this header tag is closed here now you see the important thing over here in the main component as I said that the basic principle of reactjs that you have to compose your or decompose your complete application into multiple subc components so at the top there will be a parent component and there will be sub branches or branches of that particular component so the first component the parent component is app inside it I have called three different components one is the demo class another is author and another is CMP style so first this demo class subcomponent will be called with this this subcomponent a prop is defined a prop or you can say parameter is defined with the value react classes the value of this particular you can say prop it will be used in the definition of the demo class component so if I go to the demo class since it’s a class component it should Implement a render method and a return statement so how you can use the props you can use the props by using this do props so that is how it is used over here this do props and what is the attribute name the attribute name is the demo class the second subcomponent which is called is the author now author again has a attribute called author name which is used in this component class author extends component render implementation and then a return statement this. props do author name which means that whatever attribute to Define over here can be used in the component by using the syntax this doprs do attribute name now the third component is a little bit different the attribute name is a student name but here what I’ve have done is that in the render method I have applied a custom CSS just to show you that how you can use the attributes within the jsx in a cly bracket so where my style some styling has been given and in the return statement style equal to my style now this my style is put in a cly bracket which becomes a jsx statement after that I have done some calculations you can see here calculation 4 – 2 equal to it is in bracket then only this value will be shown okay now to run this create react application if I go to package.json file so what is package.json so package.json you can say is the introduction of any react based application or you can say the basic information of that react based application so it gives me about the name about the version about the private dependencies and the scripts so there are some default scripts at the same time you can create some custom script of yours so there is a script called start so if I have to run this complete project or application how I have to write it so in the nodejs command prompt I have to write npm start so I have clicked enter and this will open the browser on the local host on the port number 3,000 so now you can see here the output that there was a header in the header there was a image a text and this is react classes by wej and you can see the calculation has been done because we place the attribute the complete jsx or you can say JavaScript expression in the cly bracket so this is the output of this particular code which I showed you in app.js now the beauty of this particular application is that whenever you will change the code whenever you make some changes you don’t have to run the npm start again and again the changes will be reflected on the browser instantaneously so you can say that this particular application is very much reactive in nature so whenever you change the code or update any code it will directly get reflected on the browser okay so let’s go to index.js and start making some changes in the code so I’ll start with again basic jsx elements so that you can understand how we can write jsx this is a very simple example again react dom. render H1 hello world so if I go on the screen I have not saved it if I save this file and if I go to the screen it shows me hello world I have not refreshed the screen it’s very much reactive in nature okay now let’s talk about some more examples we’ll quickly see some more examples jsx I’m just showing you as of now jsx props and components examples once this will be completed then we will talk talk about State life cycle events and the remaining concepts of reactjs so in this particular example how you can add your jsx in the previous example if you have seen that in the react dom. render I have added the complete element as the first argument for react dom. render but there is one more practice which you can follow that instead of writing the complete jsx or HTML expression in the react dom. render first parameter what you can do is that you can create a element outside the reactdom do render and then pass that element in the react dom. render method so what I’ve done is that I’ve created a dummy text and created a const element in that I have created a div structure in that div structure what I’m doing is that I’m creating a button class name equal to button the text is button and then a sample text will be displayed once this constant element or you can say AJ expression is created I can pass this to react. render like this so let’s save this file and see the output you can see the output that there is a button and some sample text shown on the screen so this is the best practice you can say to write the jsx expressions or jsx elements because your jsx elements can go bigger and bigger if it is a single line jsx expression or jsx statement you can very well write it in react. render but if it is very big or going to become very very big then you can put it outside react dom. render in a constant element and then you can pass the react dom. render that element just like shown on the screen now we will see the example how you can render the elements using jsx now how you can render the elements using jsx now in this particular example please remember that every react application it should start from react. render so how the data flow goes It goes from react dom. render so first we will see what is passed over here the element which is passed is const element now in this const element what we are passing is in H1 hello format name and we have passed props as user now what is format name you can see that format name is used as a function component the parameter passed is user and for this user the properties using the arrow function here the arrow function is used the properties for this user user. first name and user. last name is used as in the arrow function which are passed to this particular function as the properties so return user. first name and return user. last name and in the react dom. render I’m calling this element so let’s save this file and what output it will give me it will give me the hello user hello format name format name is calling a user so user is whle Jen so hello vle Jen because whle is the first name and Jen is the last name so let’s close this quickly now let’s talk about some other example that how you can render the elements in reactjs now we’ll start with reactdom do render in reactdom do render there is a parent component which is clock now what is happening in this clock is that this clock is declared as you can say class component so class clock extends react. component a Constructor a super is defined and we are setting the state this do state please remember state is always set the initial state is always set by using this do state and in this do state we are passing date as a new date in the component did Mount and component will Mount we’ll talk about this later because these are life cycle methods in this just we are calling different different methods and we are setting the state in the tick method tick function we are setting this with the date new now what will happen that in the render method there is a H1 hello whle and in the H2 how we set the state please remember that we set the props using this. props do attribute attribute name and this likewise we set the state this. state. attribute so here what I’m doing this do set state. date. to local string which will show me the current date or time so hello whle it is 10:36 p.m. that is how we can set the initial State and final state in reactjs now components and props now let’s talk about what are the components and props so we already saw that in react n. render we can pass the element but in the element again instead of passing the complete jsx statement we can pass it as a component so you can see over here const element in the previous example I showed you that in the element there was a jsx expression having some div some P tag some H1 tag but in this particular example I’m passing a component to the constant element the component name is welcome having some attribute called last name now in the definition of this particular component which is function welcome I’m returning H1 hello props do last name now what is last name gen so let’s save this and let’s check the output you can see here hello last name this is my last name that is how you can render the components and props in reactjs it’s very simple very straight forward in nature now this is just an interesting one having some null value so how you can conditionally render a react component this is very important to understand that in element I have a component called message having attribute message having the value as null now in the react. render I’m passing this element and calling the message component so let’s save this file and see the output so there is no output you can see on the screen because I’m passing a null value so you can also conditionally render a react component so let’s move to another example that how you can style the react component very very important to understand that how you can do The Styling in the react component because please remember just like in Native JavaScript and jQuery we ed class class equal to some name to let’s say style any tag or component in JavaScript of jQuery but in react we use the class name this is a keyword so instead of class class we use class name so this class name I have defined in index.css so if I save this and see so you see here this is the CSS which is defined and the text rendered is Whipple box because the text is given over here is Whipple boox so this is a box small you can say a class which is defined so if I go to in index.css this is the Box small class which is defined so defining the class in CSS it’s pretty same by the dot by the dot operator you have to define the class but for calling that class instead of class keyword you have to use the class name keyword this is very very important to understand in reactjs now I will show you a very good example of reactjs that how you can Implement a multiple choice question kind of functionality in reactjs very important to understand so let me close this so for stopping this npm start you can press contrl C on your keyboard it will ask that you want to terminate the bad job you can press yes and then press enter I’m just opening another example let’s close everything just open this in Visual Studio code a very good example we will see that again the same example uh index.js I have app.js defined and index.js in index.js I’m calling react. render in this the parent component will be called the parent component is app and here in app.js this parent component is written as a function component you can see here that it is written as a function component right so let’s run this code first of all to see it running so for running any react base create create react App application you have to use the command npm start so I have just entered the command npm start and pressed enter so it will open up in the browser so meanwhile we will see the code what is written in this function component in app.js so in index.js I have written react. render this is the parent component and document. getet element by ID where I want to display or render the output okay so let’s go to app.js so in this app.js since this is a function component I have a return statement over here in this return statement I have written some basic HTML so header tag is there so in this header tag what I’ve have done is that specified the class name because you have to specify it with the class name some image will be there and then in the anchor tag I have returned some static text so it’s running as of now it’s starting the server npm server no problem we’ll move to the code again okay now in this particular example what I want to show you is a multiple choice kind of functionality multiple choice question quiz you can say so let me just do the uncommenting and let me comment this react dom. render else there will be multiple reang dom. render I don’t want that okay so so this is the application which we want to create now the question here is that how we can create this type of application now this is a multiple choice question application which is created in reactjs now as you can see this is the output which I’m showing you now as you can see on the screen that there is a section called correct and incorrect so this is my score area you can say that this is called a score area below is is my question area now these are the two high level areas or components I have talked about but at the same time I can split this complete UI into sub components so when I say this is the score area okay or let’s say the outer complete boundary is the quiz then I have a score area in this score area I have two subcomponents the correct answer and the incorrect answer and in the question area I can have two subcomponents the question and the choices so if you see it it ask me that what is 8 into 1 if I click on 8 see the answers goes is correct and the state is changed to correct equal to 1 right so I just want to show you in this particular example that how you can decompose your UI or decompose your react application into subcomponents or you can say you can create a parent child kind of hierarchy although some advanced concepts are used to build this particular application which I’m not going to tell you as of now but I just want to show you that how you can decompose an application if it is given as a requirement or problem to you then how you can decompose it into different components so let’s go back to the code and let’s directly go to react. render now in this react. render the first component or you can say the root or the parent component which is called is the quiz component now let’s go to the quiz component where is the quiz component so this is the quiz component now this is a class-based quiz component following the es6 standard class quiz extends react. component having a Constructor super and a data set is defined with the correct answer now once this data set is defined okay now we are setting the state initial state that is this dot State and binding some click events or you can say functions to it but the most important part is the render method or which implements this component implements a render method so in this render method method in the return statement I have two subcomponents which I was telling you about that this particular quiz can be divided into sub components two subcomponents one is the quiz area and another is the score area so you can see here one is the score area which will have the correct answers and the incorrect answers and another is the quiz area now if I go to let’s say the score area score area component so if I go to let me show you the score area component this is the score area component as I told you that this again score area component can be divided into two subcomponents one is for the correct answers and one is for the incorrect answers so you can see over here that there are two other sub components total correct and total incorrect right so these are the two subc components which are called in the score area component at the top now if I show you the other one which is the question area so in the main one we have the quiz area in the quiz area I can have two subcomponents one is the question and one is the answer list so you can see this is my question and this is the complete answer list so if I say this question and if I click on let’s say wrong answer so it becomes a incorrect answer right so that is how you can divide a react application or decompose a react applications into components or subcomponents so in this particular example let me repeat one again very quickly that this particular application divided into two main components that is the question and the score area again the score area is divided into the correct answer and the incorrect answer those can be considered as two subcomponents of the score area component and then this quiz area is divided into the question and the answer list so you can see over here that this quiz area is divided into question subcomponent and the answer answer list subcomponent so these are the three important aspects and then we’ll move forward to the other reactjs fundamental which starts with States okay so till now we talked about the fundamentals of reactjs wherein we talked about es5 and es6 refactoring we talked about what are the advantages of reactjs and we also talk about some of the fundamentals like jsx components and props so we talked about these in detail that what are the various types of components we can create we can create functional components and we can create class components but going forward please remember that es6 standard says that you have to create class components only because now we are going to talk about States so what are states in reactjs so just like we have props we talked about props in reactjs which is used for data management in reactjs so in addition to props react component have another way of holding the data and which is called a state so what is the state so components can change so to keep track of the various changes or the updates happening in the component over the time we use the concept of state so in this example as you can see let’s say there is ice State changes event has happened on this particular eyes and because of this change of event State changes so what is the state or the event which is changed over here let’s say we have increased the temperature and because of this increase in temperature the ice has been converted to water so what we can say is that the previous state of this particular object was ice and when some event has happened on a component which is in this case is increase in temperature the final state has become water so for State we can say that unlike props component states are mutable because in props we talked about that react props are immutable in nature which means they talk about pure functions or they talk about that you cannot change the value of the props inside a component but unlike props the component states are mutable so as I mentioned that react components have another way to hold the data and which is called State now objects which control the components rendering and behavior so states are the one which handle or control the components rendering and behavior and you can say this is the core of any react component as you can see on the screen that component is Central to any tree and around it revolves the props and the state but the important thing is that estate should be kept simple as much as possible because we know what are props how can you compare the props and state so Props are the values which is passed in by a component parent so you can see here that the props these are the value passed in by a component parent so this value is passed to another component as a prop and the value is again passed to another compon component as a prop its state is local mutable data that can be created and modified within the component this is the definition of State you can say so state is local it should be very simple in nature and mutable data which can be created and modified within the component now what is the use of having the local data or you can say local state having local data that can change within a component increases complexity and limits the composability of the component so when we talk about props we have local data which flows from one component to another component but the problem with this is that it can change within the component and can increase the complexity and also limits the composability of any component so when we talk about state in reactjs please remember that to use state in reactjs you have to use a class component there will be no more function components in our projects if you want to use a state and in the class Constructor since we are talking about class components so there will be a default Constructor over there we will initialize the component state to a sensible default value so just to repeat once again what is a state state is just another way of holding the data in reactjs now this is something very important that components in reactjs can be in two forms you can create again two types of component one is stateless component and another is State full component now what is the difference between these two state less and state full because we talked about components components can be created by two ways now when I say State less stateless means it does not remember anything it does it does not keep track of any state and what is a stateful it remembers everything it does it keeps track of every change on an event or any update in the event now let’s talk about stateless and stateful first of all what is a stateless so as we talked about stateless means it does not remember anything it does and stateful is it remembers everything it does which means if there is any change in the state it keeps track of that particular thing or particular change or particular update because of an event now stateless it calculates the state internal state of components and what is a stateful it is the core or heart of reactjs you can say which is stores the information about the component state in memory the stateless components they never change the state but stateful components as I talked about that they can change the state because there will be a initial State and there will be a final state so they can change the states the stateless components they contains no knowledge of the past so for example if there was initial state which you have set using this do state and you want to change or update that state using this do set state but stateless components they don’t contain any knowledge of the past events only the the current and possible future State changes can be tracked and stateless components when we talk about stateful they have knowledge of the past current and possible future State changes values so that’s why they are called stateful because they keep track of the previous state also stateless components you can say they provide referential transparency that is for small inputs it will produce the same output so if you give different different inputs small small inputs same inputs you can get the same output in stateful component it receives information from the stateless components if State changes required so these are some of the basic differences between a stateless and a stateful component now this is just again a summary for this stateless and stateful reactjs components so as we talked about what is a stateless so all function-based components can be considered as stateless reactjs component but here we are talking about that when we are talking about state in detail we’ll talk about State and we’ll see many examples so we will talk about only class based components and not the function based components so that’s why we are saying over here that function based components can be considered as stateless reactjs components so stateless reactjs components so which means they are pure JavaScript functions so we don’t need to have state over there in stateless reactjs components but as per the future Trend and the latest Technologies we are using stateful reactjs components which keep track of your previous state your current state and probably all the future States so all class-based components can be considered as stateful reactjs components and stateful react J components inherits from a particular class called react. component so estate also getting inherited from parent to the child so this was the brief about the state and what are the different types of component based on the stateless component and the stateful component in react JS before going to the demo I will talk about something called set state so as we are saying that there are stateful reactjs components what does it mean so you have to set your initial State and then you will set the final state so that is the you can say current state and the future state so there is a method called set State now what does it do so you can set the initial state by using this do state but if you want to set the future state or you want to update the state you have to use a method called this do set State Now set State method it merges the new state with the old state so for example your new state value is one and the previous state value was zero or maybe false and true the latest value will become the combination of the new state with the old state so all the previous state will remain unless it is overwritten so if you are not overriding or overwriting the previous state it will remain in the memory so for example consider a state object with properties A and B having values for example 1 and two so a is equal to 1 and B equal to 2 respectively now calling set State what will happen so calling set state with the property Bal 3 and C = 4 so it will produce a new object where B will become three and C is equal to 4 but the previous value of B was two so that is how the property of a remains unchanged the property B in this case is overwritten by the new state and in this object of the State Property C is newly added so in addition to changing the state of the component set State please remember set State method is very important it also causes the component to be rendered eventually and for performance reason you can say set State calls a batch method and there is no guarantee that the state can change immediately so by this we mean that there is a method called set state by which we can set the final state of any react JS component a class component now let’s move to some demo that how we can implement this kind of functionality so let’s see this so this is your index.html a simple HTML file where I am calling a script called like button.js by using the script tag and in this like button.js script I’m using the class component and the concept of state so this is my first example or you can say first demo a very simple one to uh let you understand that how we can work with reactjs State feature or you can say aspect because react thinks of a component as State machine and you can use this. state to hold the component state so let’s write this code what I want to do is that in react. render I’m calling a component let’s say called app now I will go to app.js where I would be writing this component so this is a function component I don’t want any function component anymore I’m just commenting it and I have commented this and I’m also commenting this now what I’m going to do is that I’m going to write a component with the name let’s say app how I will write it I will write class app it will extends from a parent class called react. component and in this react. component you have to specify a Constructor which will have the parameter as props and in this Constructor you have to call Super which will return again the props to the class instance and then you have to set the initial State this is very important that how you can set the initial state by using this dot State this is the initial state which I’m setting over here and this do state I’m setting is let’s say for example light is my property and initial value is false and then you have uh event for example uh this dot handle click is equal to I’m binding this event to the class this dot handle click do bind to this that’s it so we have set the initial State and what we have done is that we have binded a event handler to this particular class now we already know that every class component will have a render method so we will implement the render method over here now in this render method what I’m going to do is that I will have a return statement so before that I’m just writing a uh variable called where text where I’m checking the state so this do state do like I will check this using a tary operator if it is true then it will show me like else it will show me that I have not liked it that’s it I just created a variable and then I will have a return statement now what I’m going to to write in this return statement I’m just writing a simple jsx over here a very simple jsx I’m going to write a P tag I’m just passing this text as an attribute in the parenthesis I’m just writing a demi text now what we are going to do is that we have method handle click which we are going to Define now so handle click based on a event and in this event what I’m saying is that I’m going to set the state now so in this particular example what you have seen is that I have created a class component which extends from react. component it should have this dot State reason being I’m setting the initial state it has a onclick event you can say which is binded to this particular class then there will be a render method which is required in this render method there will be a return statement and in this return statement I am checking the on click so on click event I’m checking over here and what I will call I will call this dot my event name what is my event name handle click now on the click of the let’s say P tag what I want to call I want to call this handle click so in this handle click what I’m going to do is that I’m going to set the state because my initial state is liked equal to false now I want to set the final State now final state is set by as I mentioned this do set state now let’s define the property over here what was our property the property name is light and what I want to Define is this dot state. like value that’s it so what’s going to happen is that I have mentioned the not so it will automatically become true because initial value like value is false so this completes my code over here let me repeat once again I’m using the create react App application in this create react App application we can change maybe the component name also so this component name needs to be called in index.js and just save it so what we are doing over here is that in the react dom. render I’m calling a component this component is defined in your app.js now in this app.js what I’m doing is that this is the like button now like button is a class based component you can see here that it is defined as class now let’s define this export default like button and this is used over here in index.js like button correct now what will happen that you have set the initial State using this do state equal to like false and in the handle click whenever that P tag on click event will be called this handle click event will be called which will set the final state of this particular P tag so what we are saying is that my initial state is false and whenever a button Buton or any control will be clicked I am changing it to true so I am changing the state of that particular control now let’s see the output of this particular application what I’m going to do is that I’m opening it in the browser now you can see that this is a static text and when I’m clicking this particular uh button like it is saying me the message that you like this just like we wrote over here you like this so it is showing me the message that you like this so that is how you can set the initial State and final state of any react component now just to repeat once again that what we are saying is that for setting the initial State you have to use this dot State and for setting the final State you have to use this do set State method just as you can see on the screen okay now we are talking about State here let me tell you that state is similar to props but only thing is that it is mutable and and fully controlled by the component because what is happening that right now we are storing our all the data in an array in a variable for example but that is a good way to start with reactjs but later on if you want some more operations or more frequent flow of data in reactjs you can think of a state so you can think of a state as any data that should be saved and modified without necessarily being added to a database so you can say state is a place from where the data comes from and we should always try to make our state as simple as possible and minimize the number of stateful components so for example if we have let’s say 10 components that need data from the state so we should create one container component that will keep the state for all of them we should not create 10 components we should create one component as a parent component and then the other could be the child components okay now let’s see more examples based on the state so what I’m going to do is I will create more State examples or state demos to show you the concept of State in detail I’m going to create a class component so class app which extends from react. component I’m using a create react app getup project Facebook project you can say and in the react dom. render I have to call this app component so let’s call first this in index.js this particular component app and then in app.js what I’m going to do is that I’m going to create a class component with the name app so first thing first first we have to create the Constructor which is passing the props and then in Constructor what you are going to do you are going to set the super keyword this is the first and most important thing to do in the Constructor and then what we are going to do in the Constructor as I mentioned that the best place to set your initial state in reactjs is is the Constructor okay so I’m going to write this dot state I’m setting the initial State over here please remember that if you have to set the initial State you have to do it with this do state in this do state you can Define n number of properties any properties you want you can Define in this so let’s define over here for example two properties one property I have let’s say for example header this is just a property I can write it text for it let’s say header from State any text you can write this is just setting the initial State and then I have one more property let’s say for example content this is my second property in my initial State and any text I can write which I can write as content from state so what I have done is that I have set the initial state with the two properties header and content this we are creating a class component now every class component you already know it should Implement a method which is called render and every render statement should have a return state so I’m saying render and then I’m saying return in this return what I’m going to do is that I’m going to Define my some custom you can say jsx so let’s define in return so for example I have a Dev I want to write a Dev in this Dev I have H1 tag in this H1 tag I will Define my one property called header and and then again I have a h2 tag where I will Define another property called content so let’s save this file now how you set the state now even you can set the state in jsx so just like this if you want to set the state in jsx you have to place this cly braces and what will be the state you want to become so it should become this do state DOT value is header because header is a property which we have already defined and here I want to say this do state dot for example content in the previous example you might remember that I used this do props do attribute name similarly in state also while using the state we can use for setting the value or showing the value passing the value to the component by using this do state so here I have two properties header and content so I can use it like this. state. header and this. state. content so let see the output of this particular example for this example what we can do is that here I am defining a div and in this div what I’m doing is that I’m doing class component or you can say creating a class component and in this what we have done in index.js that in index.js I have called this component this is my component which is a class based component please remember that while using the state always you have to create a class component and and just like we use props in this doprs do attribute name the same way you can use State just like this do state do your attribute name in this case your attribute name was header and content now let’s move to another example where we can see that how you can use State and props in one single example it’s not always the case that you have to use only state it’s not necessary you can use State and props together also so we will create this example only or we can extend this example only so what we are going to do is that I have a return statement over here where I’m writing let’s say two more subcomponents what I’m going to do is that in this div I have a div over here I’m going to Define two more sub components so my parent component will be app and then I have two subcomponents for example let’s say header and the content so instead of this H1 tag and h2 tag which I have cre created what we can do what I’m saying is that when you create a parent component so parent component will remain the same that is app I can have some child components also where I can pass the attributes or the values as props which will Define that you can use props and you can use at the same time state in one example so let’s do that so what I’m going to do is that I’m going to create two sub you can say components so let’s say one name is header this this is my one of the component and this is the prop value the attribute which I can pass like this dot state do header and then I can close this component and another component I can create is let’s say component name will be content and I have a prop I can pass it as a prop and then I can write here this dot state do content what is the change we have done over here what we have done is that we have created a class component that will be the parent component in the render method in the return statement it has two child components so we have to Define these child components now so what we are going to do is that we are going to Define these two components now so let’s define these so what I’m going to write is that I’m going to write class my component subc component name is header again it will be a class component so it is going to extends from react. component and the same component I have to create for Content so this content component needs to be defined so I have two subcomponents now one subcomponent is the header which is having the prop value as this. state. header and another prop value as this.state do content so let’s define this every component should implement a method called render in render there needs to be a return statement now in this return statement just like we Define H1 tag I’m going to Define this in a Dev here so I will say Dev and then I will say H1 now in this H1 what I want to pass is although the value is coming from a state but the value which I want to pass over here is in the form of a prop so what I want is that I will say this Dot props dot in the header props what is the name of the prop it’s header header prop similarly what we are going to do is that in the content sub component again we will have a render method and then there will be a return statement in this return statement what I want is that I want to define a h2 tag let’s take it in a container that container is let’s say Dev I want to take it in container and in this H2 I want to pass the props so what is the name of the prop attribute that is content prop so what I will say this do props dot content prop okay so what we have done over here is that in the previous example if you remember that what we did was that we didn’t Define two subcomponents okay so in place of this let me copy this somewhere and then can show you so in place of this earlier what we did we didn’t Define the two subc components what we defined was a container which was a div and in this div we had one H1 tag in this H1 tag what we were defining we were directly using the state value how we were using state. header and then in a h2 tag what we were doing we were using the content value so we were saying this.state do content now let’s see the output of this particular example first what we have implemented without using the props so let’s save this file and let’s go to the browser so now what it is saying that header from State and content from State I have already run the npm start command for this create react application so you can see the output in local host on the port 3,000 header from State and content from State why this output is coming because the header value is header from State and content value is content from State this was the direct way without using the props how we have used the props by using the sub component concept so let’s implement this subc component yeah now what we are doing is that we have defined two subcomponents which is header and content these are the two subc components class based components and we have passed the value as props now you can see this. state. header header value will come and let’s say we can write some updated value new header from State and new container from state for example and you can see the value over here new header from State and new container from State this is the output basically what we have done here is that I have showed you both the ways of using the state in reactjs which means that you can use it without props and you can use it with props also so there are you can say two ways of using state in reactjs but I will prefer I will recommend that you can use state with props and if whenever required or whenever you can say apply the props Just go with it it’s not always necessary that you have to implement every time only with the state you can very well use props and state together in the same application now just a few tips of using State and reactjs just a couple of tips from my side that do not modify the state directly don’t even try to modify the state directly you always use the set State method and the only place where you can assign this do state is the Constructor these are the two main things so what I’m saying over here is that if you have to specify this do state where you can specify this do state you can specify this do state in the Constructor only this is the first you can say right way to use the state now what is the other thing that State updates may be asynchronous in nature so react May batch multiple set State calls into a single update for performance because this. props as we use here this. State and here we use this. props so this dot props and this do state may be updated sometimes asynchronously so you should not rely on their value for calculating the next state so if you want to set the value of the next state don’t rely on the value of this do props or this do state and the third thing which I want to tell you about state is that State updates are merged when you call set state so what happens is that react merges the object you provide into the current state so these are some of the tips you can say from my side for using State and reactjs so let’s come back to this PPT and let’s talk about the another aspect of reactjs which is life cycle now what is life cycle in reactjs or what is the use of adding life cycle method to a class component in reactjs react provides various methods which notifies when certain stage of life cycle occurs called life cycle methods so there are many methods in uh reactjs which notifies when any stage of a life cycle occurs now what are the different phases of that life cycle so it start with initial phase then it comes to updating phase and then props change phase and finally the unmounting phase where you can can free out some of the resources so what we are saying is that there are four phases in which you can Define the life cycle of a particular reactjs application so what happens is that it’s very important in the application with many components let’s say there are 10 components in a reactjs application it becomes very important to free up the resources taken by the components when they are destroyed so for example a component is destroyed so it becomes very crucial very important to free up the resources which are taken by that component because once it is destroyed so the resources which has it consumed should get freed so that’s why we can declare some special methods over the component itself or you can say we can decare some special methods on the component class to run some code when a component mounts or when a component Dismount so these methods are basically called the life cycle methods Let me Give an example comp component did Mount this is a life cycle method example it runs after the component output has been rendered to the Dom so let’s talk about these different different life cycle methods in detail now so the first phase in the life cycle of any reactjs application is the initial phase now what are the different methods available out here because in this phase component is about to make its way towards the DOR it has not yet reached the DOR it is just creating its way or about to make its way to the dwn this phase you can say consist of the following methods which are invoked in a predefined order so the first method is get default props get the initial State component will Mount render method we talk about and the component did Mount and as I mentioned that component did mounted method runs after the component output has been rendered to the Dom so different methods they have their different you can say usage in any life cycle of a reactjs application now if I talk about the second phase that is you can say the updating phase when it phase comes into picture so once the component is added to the D because in the previous phase that was the initial phase so we what we said that we talked about that the component is making its way or it’s on its way towards the Dom but now since it has reached the Dom it is added to the Dom they can update and render only when a state change occurs so basically in the updating phase once the component is added to the Dom they can update and rerender only when a state change occurs so this phase consist of the methods for example should component update component will update render and component did update so please remember render is a common method in almost all the phases or the life cycle of a reactjs application so we have talked about here the initial phase we have talked about the updating phase so please remember that neither parent nor the child components can know if a certain component is stateful or stateless and they should not care whether it is defined as a function or a class but the most important thing is that when we are dealing with State our component should be of a class type it should not be of a function type so that is why you can say state is often called as local or encapsulated so it is not accessible to any component other than the one that owns and sets it a component may choose to pass a state down as props to its child components just now we saw the example of the state and props now let’s talk about the third phase that is props change phase so we talked about the initial phase we talked about the updating phase now what happens that after the component has been rendered into the Dom so in the initial phase what it was doing it was making its way towards the Dom in the initial phase in the updating phase what it was doing that it has been rendered on the Dom the component has been rendered on the D now the third phase is props change phase after the component has been rendered into the Dom the only other time the component will update apart from the state change is its props value changes so please remember that through State we can change the value or through props also we can change the value just like we saw that this do props do attribute name for example this doprs do name just like that we can say that this do state. attribute value just like we saw in the previous example so what we are saying over here is that this do props do attribute name can change can make the changes in the component and this. state can also make the changes in the component now what are the various methods which get invoked in this particular phase in a predefined order component will receive props should component update component will update and component did update of course render is a common method in every phase of the life cycle of a react application last phase in the life cycle of a react application is the unmounting phase this is the last phase of the component life cycle in which the component is destroyed and removed from the Dom this is called unmounting so we were talking about the mounting and the unmounting mounting means when the component is added to the Dom and unmounting means when the component is removed completely from the Dom and this phase only consist of one method no render method over here the only method which is there in the unmounting phase of a reactjs application is component will unmount now let’s see how the life cycle goes in a reactjs application so we talked about the initial phase we talked about the updating phase we talked about the props change phase and then we talked about the unmounting phase so these are some of the methods which are mentioned over here so it started with the initial phase where we had the method called get default props then get initial state will be called component will Mount will be called and then render will be called and then component de amount will be called as I mentioned that all these methods always called are called in a predefined order so please remember that if you write a method let’s say for example get default props and component will Mount so you should understand that in which order it will be called so first of all get default props will be called and then component will Mount will be called now you can see on the screen that once this initial phase is done what we have the other phase that the props can change the state phase and then we have the update phase we are different methods could be called so what are the different methods that component will receive props should component update component will update render and component did update so these are the different methods in the update phase now if I talk about the last phase which is the unmounting phase so what happens that reactdom do unmount we call the component will unmount method for the unmounting phase for completely removing the component from the Dom that is the last phase or there is one method which is called over there which is the component will unmount once the component is completely unmounted or destroyed from the domor again the life cycle start from react dom. render and again the get default props methods is called so that is how this complete life cycle again goes on and on now this is the description of these life cycle methods which we talked about so so we talked about component will Mount component did Mount and so on so what happens with component will Mount is that it is fired once before initial rendering offers and it is a very good place to wire up your message listeners please remember that this do set state does not work here the other method in the life cycle is component did amount it is again only fired once in any reactjs application after initial rendering occurs it can use this. getd node so what is happening over here is that component will Mount will always be called before the rendering occurs and component did Mount is fired after the initial rendering workers so there is you can see very a minute difference between component will Mount and component did Mount will means uncertainty so it is going to render or the initial rendering has started but it has not been yet rendered on the Dom and component did Mount means it has rendered on the browser or on the Dom it will be fired once the initial rendering on the Dom occurs the third method is component will update it is fired after the component updates are made to the Dom you can use this.g Dom node for updates over here the other method is component did update now what happens with this method is that it invoke immediately after the component updates are flushed to the Dom so any change any update is there in the component it gets flushed to the Dom then you can call component did update and this method is not called for the initial rendering please remember this is very important that for initial rendering of the reactjs component component de update method is not used you can use this as an opportunity to operate on the Dom when the component has been updated so for example it has been updated using the props or using the state then only you can use component did update component will unmount we already talked about this that this is a single method which is called in the unmounting phase of the life cycle of a reactjs application it is fired immediately before a component is unmounted from the Dom and it’s a very good place to remove message listeners or you can say General cleanup or Garbage Collection kind of activities you can do in component unmount method another is component will receive props it is fired when a component is receiving the new props you might want to use this. set State depending on the props just like we saw that we can use both props and state in a single application the other is that should component update now this is pretty interesting that this is fired before rendering when new props or state are received received it will return false if you know an update is not needed so you can check on any of the component based on the state and the props that if any update is required or not and accordingly you can return false and true based on this method which is should component update now this is very much interesting Constructor we talked about Constructor that whenever we are using the class component in react JS you have to use the Constructor you have to pass the props and then you have to use a super keyword now what what is this Constructor in props that if you don’t initialize the state and you don’t bind the methods you don’t need to implement a Constructor for your react component and ultimately we already talked about this will be converted into function based component but here we are talking about state so our focus is for class components please remember if you are not binding anything in your component if you are not using any state then you don’t need a Constructor in your class the Constructor for a react component is called before it is mounted when implementing the Constructor for a react component subclass you should call the super keyword before any other statement because if you will not call the super what will happen that this props will become undefined in the Constructor which can lead to errors or exceptions or bugs in your application so that is why it is said that the super keyword should be called before any statement in your reactjs application so first you have to call the Constructor and then you have to call the super keyword so that this do props should not become undefined so what we are saying is that typically in react class based react component you can say Constructors are only used for two purposes specifically it is used for you can say initializing the local state or you can say initializing the initial state by assigning an object to this dot State and then what we are saying is that for binding the various events or binding the event handler methods to an instance of the class you need the Constructor please remember these are the two basic purpose of using Constructor so if you want to set the initial state that will be done in the Constructor if you want to you can say bind even Handler methods to the class instance that will be done in the Constructor of the class now this is just uh you can say pictorial representation of the different phases now if I talk about the life cycle of any react application it revolves around the three important phases mounting updating and unmounting so what we are saying that first you add the component to the Dom you do some changes or updates and then finally you unmount it so what are the different methods which are shown on the screen you can see that what are the different methods we generally use while mounting updating and unmounting so in the mounting we place the Constructor we can call the method called component did Mount and then when it comes to updating phase we can use three different types of methods new props for get derived state from props or should comp update we can use this. set State and we can use dis. force update and the different methods which we can use in the updating phases component did update and finally in the unmounting phase there is only one method which we can use which is component will unmount so this is just a representation you can say summarized way of representation of the life cycle of a react component so we talked about till here jsx we talked about components props States and life cycle now another important aspect you can say a very important fundamental of reactjs is events so what are events events are the you can say triggered reactions to specific actions so for example we can have onclick event we can have Mouse click we can have Mouse hover key press all these are called events and react CHS so for example there is an action so some action happened on the react component and then we have a react application which is called event now some event has happened on the react component and it becomes a reaction so that is a definition of events now first we talk about that how the concept of event work in other uis as compared to reactjs and then we will talk about that how events work in react GS let’s say I have a control let’s say three controls or many controls button type control now what happens that in other uis on every control you have to implement a event listener as a corresponding event handler this is very much required which decreases the performance of the application on the Dom because what is happening over here is that for different controls just like
shown over here that you have a different controls different buttons or maybe another controls you have to implement the event listener on every control and when a event listener is implemented a corresponding event handler will be required so that is how the different uis or other uis work when it comes to events now let’s talk about events in react how react manages events in react so what happens is that if you have different controls then you will have only one event listener and one event handler attached to it so which increases ultimately the performance of reactjs application please remember that react events are named using camel casing rather than uh lower case so you have to Define events or you can handle the events with camel case only and with jsx you can pass a function as the event handler rather than a string so we will see that in the demo so before moving to reps now the other fundamental of reactjs let’s see some of the demo of handling events in reactjs so for that I’m going to show you a example we have talked about State we have talked about props and jsx and all that stuff so this is just uh you can say playground which I generally use to work with reactj which is called pen.io so in this particular example what I’ve done is that I’m using a conditional rendering based on my click or you can say based on my event so we’ll start from react doom. render so this is the react doom. render which is calling a parent component which is login control now if I go to login control which is a component now in the login control it is a class based component which is extending from react. component now every class component if it is binding something or setting the state it should have a Constructor it should have a super keyword so that this do prop should not become undefined now here you can see that I have defined two event handlers for binding in the Constructor of the class one is handle login click and handle logout click I’m binding it over there and setting the initial state that is logged in is false so initial state is is logged in is false that the user is not logged in as of now now that is why you can see that it is saying in the output that please sign up and showing me the button of login what is happening in handle login click and handle log out click we’ll see later first we will see the render render method implementation in the render method I have declared a constant is logged in equal to this do state do is logged in now what will be the value in this because it is initially set to true you can see here initially set to it is false and then in the events what I’m doing is I’m setting it true or false so first of all it will take the initial value I’m taking a let button and if is logged in if it is true then this button will be called where I’m calling a component called logout button and if it is false then I’m calling another component which is again login button if it is true then log out button if it is false it is login button now you see over here on click this is called event in react js on click is a event this event l listener is bounded to a event handler so this is binded to a event handler which is handle logout click and this is on click event is binded to a event handler which is called handle login click so we’ll see what is happening in handle login click and handle logout click in handle login click we are setting the state and we are setting it to true and in the handle log out again the user will be logged out so we are saying that is loged in is false so let’s see the implementation so what is happening that if I click on login it is showing me the message welcome back you can see on the screen so function user greeting is called welcome back and when I’m clicking on the button again log out it is saying me please sign in you can see over here please sign up so what is happening is that in the login button and log out button so I have two function components login button and log out button so what I’m doing is that I’m again calling the event that is on click equal to props do on click and in the greeting method what I’m checking is that if it is logged in then it will return another component user greeting which is again a function component and then if it is logged out then it will say guest greeting again which is a function component so that is how you can use events in reactjs now let’s see another example of using events in reactjs so what we can do is that we have to start from react. render in the react dom. render what we are doing that we are calling a component which is tole so this will become my parent component now in this strle what I’m doing is that I’m writing the Constructor that is very much required for a class component because I’m setting the state then there is a super keyword in the this. state I’m defining a property is loged down true so is toggle on is tole on property is always true and I’m binding a event this do hand click so this. handle click. bind to this particular class and in this handle click event what I’m doing is because I have used a button on the button I calling an event now what is the event onclick on click event what I’m doing this do handle click and in this what I’m saying is does this do state. Isle on what will be the text of the button so when I will click if it is true it will be on if it is false the text will be off so let’s see the output if I click on this button the text becomes off if I again click on it the text becomes on so this is just a text of the particular button which we are changing based on the state so this. state do Isle on so what we have done is that we have set the initial State first of all initial state is true so whenever it will be true this do state. is struggle on whenever it will be true the text shown is on once I click on it now the this do state. is struggle on becomes false and whenever it becomes false the text is shown as off so that is how we can work with the basic all the fundamentals we can apply in one application it’s not like that in reactjs that you have to come up with only jsx based application or component based application it’s not like that all the react fundamentals which we talked about over here should be used every time in combination then only you can learn reactjs in detail so what I’m saying is that you can apply jsx components props State and then life cycle methods and some kind of events for example onclick events just we saw all these things you can combine in one react application so let’s see more examples of events so what I’m doing here is let me remove everything from here okay so let’s create a parent component app for a very simple example of the events so what I’m writing over here is that class app extend re. component I have to define a Constructor The Constructor I have to Define props I have to use the super keyword so that this do props does not become undefined so what I want to do is that I want to set the initial state with this do state and then I want to use I can use here this Dot update State also so update state will be my Handler and I can Define the update state so what I’m doing is that this dot update state do bind and I want to bind this to this particular class uh let’s remove all this okay so let me copy this particular toggle example from here what I want to do is so in this particular index.js let me Define this toggle so what we have done is that we have defined the same component toggle over here and in this toggle what we have done is that we have implemented a Constructor as I told you okay and then in the Constructor what we have done that we have binded a event and initial value of the toggle is true and then the final value on the click of the you can say button I’m setting the state as this do set state where I’m changing the value called is stral on from True to false now let’s talk about child events what is the concept of child event in reactjs so when we need to update the state of the parent component from its child so generally what we have learned till here is that you can update the child even from the parent but there could be some situ situations when you need to update the state of the parent component from below that is from the child so we can create a event handler for example let’s say update state in the parent component and you can pass it as a prop to the child component where we can just call it so let’s do that so what I’m going to do is let’s index.js go back to index.js and let’s define a component with the name called app and in the app.js what I’m going to do is that I’m going to define a class component with the name app which extends from react. component so this is my class component which I have defined now in this I have to define the Constructor with the props and in this Constructor I have to define the super keyword so that this do props should become undefined now in this super we have to let’s say uh Define for example I have to Define initial state so what I’m going to do is that I’m going to say this do state is equal to so I have to define a property property could be let’s say data and I have to Define some data over here let’s say I say it to initial data this is my initial data so my Constructor is done now I can write here let’s say for example end of class this is just my hand of Constructor so that you can understand well now let’s bind a method to this Constructor if you want to bind a method you have to bind it inside the Constructor please remember so let’s say I want to call update State this is just a method name you can use anyone of your choice any name this dot update State how you bind it you bind it using the keyword bind and this so by this statement what you say because you have to Define this inside the Constructor by this you are binding a method which is called update State and we are defining now the update State this is a method we are defining and in this update State what we can do we can set the state now what state you have to set so you are going to set the value of let’s say data because that is the property you defined and let’s say what we want to do is the data for example updated from the child component something like that could be of any text no problem at all so this is the end of the update State method now you have to implement always a render method now once you have implemented a render method it should have a return statement so we are using a return statement over here so this is my end of render method and this is let’s say end of return statement okay now in this return what I want to do is that let’s say create a container so my container is div and in this particular thing what I want to do is I want to define a sub component because in this particular uh demo what I’m going to show you that how you can update the state of the parent component from a child component so I need to have a child component over here so I’m going to define a child component which is let’s say name is content and I’m just taking a prop value over here with the attribute my data prop and I’m saying value of the initial value of the state is this do state my attribute name is data and then what I’m seeing is another prop I’m using is update this is the another prop you can use multip M props multiple attributes and I’m saying is this do update state so what I have done is that I want to update the state of the parent component my parent component in this case is app and I want to update the state from a child component which is the content so this class is over here and then I want to define a sub component a child component because we have not defined it yet yet so I will write class content my component name child component name is content so I have to Define over here so I’m saying class content extends react. component and what I’m going to Define here is uh Implement a render method and in this render method I will have a return statement that’s it now in this return statement what I want is let’s say I have a container a div again and uh for example let’s say I want to add a button and button will have let’s say on click event and on the on click event I want to call the props so what is the props attribute I want to call this dot props dot the update State prop update State prop I want to call this button is closed and let’s say the name of the button is as of now give it click now one more HTML tag let’s add one more HTML tag to use the another prop attribute and that is this dot props do my data Pro that’s it let me tell you that what we have done in this that in reactjs when we need to update the state of the parent component from the child component so here you can see on the screen that I have created here two components one is the parent component which is the app component and another another is the child component now what happens is that what you can do is that you can update the state of a parent component from its child generally what happens in a general scenario that a parent component updates the state of a child component but in this particular example what I’m going to show you that how you can update the state of a parent component from a child component so what I have done is that I have created a event handler update state in the parent component you can see that this particular event handler this is created in the parent component but it is passed as a prop to the child component you can see over here this particular event handler is passed as a prop to the child component so let’s see the output of this I’m saving this I’m just clicking and when I clicked it the button was there in my child component you can see the state has been changed and it is saying that the data has been updated from the child component you can see over here which means that the event handler which we created in the parent component can be passed as a prop so one good learning from this particular example we can get that the event handler which you are creating can also be passed as a prop and that prop can be used in another subc component or child component now another thing which I want to tell you that how you can prevent component from rendering for example there could be cases where you don’t want to render a component or you don’t want to hide a component all these are rare cases but in rare cases you might want a component to hide itself even though it was rendered by some another component so for that what we do generally is that we return null instead of its rendered output that is the only trick by which we can prevent a component to render on the Dom that you can return null instead of its rendered output now what we will do is that we can see the component events that how events are created in components so this I have already shown you let’s go back to the slide now and let’s talk about some other fundamentals so refs now we will talk about refs what is a ref in reactjs so ref stands for references you can say ref provide a way to access Dom nodes or react elements created in the render method this is the definition of refs so what I’m saying is that ref stands for references and they are used to return the references to a particular element or you can say component returned by the render so if I have a react element having a render method I have to place some reference in my component so by using the ref keyword I can place a reference to that particular component in reactjs so what happens that in the typical react data flow props are the only way that parent component interact with their children so what we have seen is that in reactjs probably if you want to pass the data or you want to flow the data from parent to the child props are the only way to modify a child you rerender it with new props however there are few cases where you need to you can say imperatively modify a child outside of the typical data flow so the child to be modified could be an instance of the react component or it could be a Dom element so for both these cases react provides an escape hch you can say and which are called refs now the important thing is that when to use refs so there are particular cases you can say few good use cases for using refs those are you can manage the focus you can manage the text selection or you want to apply a media playback there you can apply the refs you can apply the refs in application where you triggering imperative animations or you are integrating with third party Dom libraries probably there you can use very well reps so important thing is that avoid using Reps for anything that can be done declaratively now how you create the Reps reps are created using react. Create ref method and they are attached to a react element via the ref attribute so ref is a attribute refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component so this is very much important about react ra now if I show you that how you can use the refs so let me go back to the same example now ref is used to return a reference to the element this we have already known now what are the react WS although I will recommend that refs should be avoided in most of the cases however they can be useful when we need Dome measurements or to add methods to the components so we will see now that how you can use revs in this example I’m going to show you that how you can use revs to clear the input field okay so let’s remove everything we have a Constructor props this. State let’s remove this method and let’s remove this render remve this class okay so we are using the same app component what we are going to do is that we have a Constructor with a props keyword and the super keyword with props we have the initial State called this do state having let’s say for example some blank data in this case and then you have this. update State equal to this. updat State dobine and let’s have one more you can say Handler event handler which says this do clear input equal to this do clear input. bind this this Constructor is closed over here let me save this file and then I’m going to Define this update state update State event handler we have to Define so I’m writing here update State let pass argument to it and then I’m setting the state as so this do set State what is the value of the property value of the property I have to Define over here okay the value of the property is data and in this data what I’m doing is data value should be e do Target do value so we have defined the update State also that whatever value will be the input will become the set State value now we have to Define another method that another method is clear input so let’s copy and paste over here I have to define the clear input method now in this what I’m saying is this dot again I have to set the state so I’m setting the state same value I have to use and that is data so I am making it again Plank and after that I’m finding the Dom so how you can find the Dom reactjs is react Dom dot you have a method or you can say function called find Dom node so I want to find the Dom node and how can I find the Dom node I can find it using ref so what I’m saying is this dot refs I’m just taking a input value that is my input text box which I’m going to Define in the render method what I will do that I will use the focus method for this this is my clear input function and finally we have the render method Implement for the class and in this render method you have to apply the return statement the return statement we are going to write some HTML or jsx so I’m creating first of all the container my container is div I’m taking an input type value equal to this. state. data so that will be the blank value initial value this do state. data I’m taking a event over here on change so whenever there will be a change in the text box this method or this event will be called and in this I’m calling this dot update State and I’m also defining the ref which is very important ref is which I have defined here my input so on my input the ref will work so this input is defined so this text box is defined and now I will have uh button control where on click event needs to be defined so I’m defining the onclick event the name of the button is clear so on click what I want to do is that I want to call a binded method which is this do clear input and after that simply I want to place a H4 tag in this H4 tag I will show the final State value by using this dot final value how can I show that this do state do data so this completes my explanation of the Ws where what we have done is that we have created a component called app in this particular component what we are doing is that we are setting the initial state with a blank value and I have called two event handlers you can say this do update State and this do clear input now in the update state I’m setting the value what is taken as an input from the user in a you can say text box and then in the clear input what I’m doing is that whenever this clear input will be called I’m setting again the value to be planed but in this case what I’m doing is that I’m making a focus by using the ra on that particular textbox control or you can say input control now in the return statement in the render method I have taken a text box or you can say input control which is have some value then there will be a button so let’s see the output of this particular application so if I write let’s say vull and I click on clear you can see it has been completely cleared from here so that is how you can uh use ref in reactjs okay now we’ll talk about example or you can say a demo a project where the concept which we have studied till now are let me repeat one thing jsx we talked about components props State life cycle events and Reps so out of this eight important fundamentals of reactjs we have already talked about the seven important aspects but before moving to the last reactjs fundamental that is keys that how you can use keys in reactjs let me walk you through a very good example or you can say a small project so the project requirement starts with this particular you can say example so in this example what you can see is that you have to implement a search functionality where users can search from this particular text box and whatever they are going to search it it will be visible on the screen with that search result or that search keyword now what should be the approach of yours to implement this kind of reactjs application now what is the step one my recommendation is that you break the UI into different components or you can say component hierarchy when I say component hierarchy what does it mean that you break the comp complete UI because reactjs is all about UI so you break the complete hierarchy into components component hierarchy which means that there will be a parent component there could be child or subcomponents and there could be Sub sub components so first thing first what you want to do that you will want to do is to draw boxes around every component so in this particular example what I’ve done is that I have created different colored boxes around every component and sub component component and I have given them some names also but the problem is that how do you know what should be its own component okay so by coloring this particular example we can see that there are five components in this very simple application it’s a very simple application where there could be five components so one component you can see this outer boundary of orange color so let’s say I call this as filterable product table which contains the ENT ity of the example now there is a search bar this could be my second component in the blue color the blue boundary you can see it receives the user input now there is a product table you can see the Green Boundary this is my third component this is called let’s say the product table which displays and filters the data collection based on user input now another is product category row you can see here the San color sporting goods and electronics this is my product category row which displays a heading for the each category this is my fourth component and the final component is the product row which is in the red color which displays a row for each product so now we have identified the components in this particular example now if I want to arrange them into hierarchy because components that appear within the another component should appear as a child in this particular hierarchy so what should be my hierarchy the hierarchy to break this component the particular UI is at the top I will have a filterable product table then there will be two subcomponents search bar and the product table and in the product table I have product category row and the product row so that is how we can build any reactjs application now let’s build a static version of this in react okay by creating you can say uh different different components so just want to add one thing that if if you want to make your UI very much interactive you need to able to trigger changes to your underlying data model and we are going to use it because this particular application can be made easy with the help of State what is our state the search text the user has entered this is the state and the value of this checkbox because I have added a checkbox also over here so let’s create this particular example in reactjs application so before creating this I have a sample dat dat you can say a mo data which can be used for this particular example so let’s start creating this particular application in reactjs so I’m just removing all these stuff from here let’s create this example and see how it works while using in reactjs so let me close this and I’m going to open a new instance so I’m going to open it in visual Studio code or else what we can do is we can try this example over here okay so what we are going to do is now that we are going to see that search example in this particular demo so in this particular example we talked about that we will divide the complete UI or complete example into five different components so let write those components in the create react App application so for that I have a dummy data in this dummy data what I’m going to do is first I have to create a class component the outermost that is the orange one for example let’s say filterable product with the name filterable product and I’m writing extand react do component so this will be my parent component out of the five components this will be my parent component so I’m just writing the Constructor for this class please remember all the initial State and binding of the methods needs to be done always in the Constructor only so once this is done I’m initializing or setting the initial state by using this. State you can always use this. State and can apply the properties so what are the properties I want to use the properties which I want to use is for example let’s say filter text having initial value let’s say blank and another property which I want to use is in stock only I want to check whether the products are there in the stock or not initial value let’s say false now what are the different methods which I want to bind the methods which I want to bind is for example let’s say this dot handle filter text change this is just a you can say name of the event I have to bind it to the class so I will say this dot handle filter text change dot b to this and after that what I will say this dot handle another event handler I want to bind to this particular class please remember all this needs to be done inside the Constructor only I don’t want handle filter exchange I want this time handle stock change and I want to bind it that’s it so we have defined the Constructor we have defined two or you can say we have binded two methods now it’s time to Define them so first one is handle filter text change and another is handle in stock change so these are the two methods which we are going to Define now and after that once these are defined the final thing is that you have to implement a render method for this particular class so first set the final state in this so This dot set State and there will be this dot set state so in the handle filter text change so whenever there will be a text change I want to set the final state so handle filter text change I’m going to pass text property and then I’m going to set the state so with which value I will say that filter text will be whatever be the value of the filter text now the second method which I want to bind is handle in stock change so I will have another property for it that is inst stock only and in the this. set State what I want to do is I want to set the final value of this particular property which is in stock only so I will say in stock only the property will be what whatever we passed to it that’s it so I’m done with binding the events in the Constructor setting the initial State and setting the final state in the two event handlers now the final thing is to implement the render method so in the render method I will have return statement so let’s close this return and in this return what I’m going to do is that I’m going to Define first of all a container let’s say I have defined a container now the important thing in this container what I’m going to do is as I mentioned that that I have total five components in this particular search example I have five components to be defined and this is the first component on which I working so what will be the other subcomponents other subcomponents let’s say is the search bar and another component would be the product table so you can see on the image that there is a blue boundary for the search bar component and there is a Green Boundary for the product component so let’s create those or call those components so search bar I’m saying that filter text what will be my filter text it will be this dot state do filter text now I can Define more you can say Properties or the values which are available in the initial State what are those values which are available in the initial State I have let’s say inst stock only I can Define the instock only over here what I will say I will say this dot state do instock only and then on filter exchange what I can do is that I can call my Handler what is my Handler my Handler is this. handle filter textchange and on on instock change I can again call a Handler which is this. handle instock change so that is how you can define a search bar component so this is one of the component which is defined or you can say the sub component which is defined over here the another component which I want to Define is product table so another component which I want to Define is product table now why product table if you see in this particular example this green one is the product table component and the blue one is the search component so what we have done is let me repeat once again that I have divided this complete application this complete project into five components so the first component is the first one that is filterable product table the second one is the search bar and the another one is the product table so we are as of now just calling the product table component sub component so let me Define some properties for it for example let’s say products what will be my products so I will say this do props which I’m going to Define this doprs do products so I have to Define much more values for it one is products so another let’s say I want to Define what is the filter text in this case filter text will be again same this will be this do state. filter text and then I want to Define one more property for this component that is inst stock only what will be the value of this inst stock only the value of this inst stock only will be this dot state do instock only so that is how we have defined our another sub component which is product table now as you can see how we are modularizing this particular code so first of all we are calling this filter product table in this filter product table this is the main component we are calling two sub components which is search bar and the product table so this is the main component and let’s define the main calling that is react [Music] dom. render and this in this rea dom. render what we are going to say we are going to say that we are calling the parent component what is the name of my parent component it’s filterable product table I’m going to call it and I’m going to call it on a prop what is my prop now prop is the values the Json data which I’ve already defined my prop value will be equal to products so I will say react dom. render prop value products equal to product so just I have to close this first and in fact I can close it with closing tag and then I will say document. getet element by ID the ID which I have to Define where I want to render my output that’s it so we have called the parent component by using re. render here we are passing the props as products which is my sample Json data this is the sample Json data the category of the product the name of the product and what is its price so filterable product table is the first component which we have created which is our base component or you can say parent component now the other components which we are going to create is the search bar which is the sub component and the product table component so let’s start creating those components as well so what we are going to say is class name of the component is search bar so the name of the component is search bar which extends from react. component so this is my another component and one more component which I will have which is again a sub components you can see which we have created is a product table so we can just write here class product table extends from react do component so you can see we have also created these two subcomponent which is the search bar and the product table now let’s focus on the search bar that how we are going to implement the search bar component so in the search bar component the same thing we are going to first write the Constructor and in this Constructor I’m going to define the props once this is done I’m going to call the super keyword which will have again props so this we have done now multiple times and if you want to bind some some event over here in the search bar then you can bind it over here itself so what I’m saying let’s say I want to bind couple of events over here so I will say handle filter textchange handle filter textchange so let’s say this dot handle filter exchange do bind to this and I want to have one more event handler which is handle and stock I want to check whether there it’s in stock or not so I will say this dot handle in stock do bind and this so that is how I have defined the Constructor once I Define The Constructor I have to write the definition of these events which I have written so first of all handle filter textchange this is the handle filter textchange and the another one is I want to have handle in stock change so let’s write handle in stock change now in the handle filter textchange what I want is this dot because I have the props so on filter textchange I want to pass the value which is written by the user in the text box so e do Target do value this is the value which is written by the user in the search and in the handle inst stock change what I will say that this dot DRS dot on in stock change what I’m going to write is that e do Target whether we will check that checkbox is checked or not now once this is done we will implement the render method for this particular component so I will say render and then I will have a return statement which will allow me to write the jsx for this particular class so let’s say I use a form element of HTML and then I want to implement a textbox kind of functionality so for implementing this textbox kind of functionality I’m using input input type type will be equal to text placeholder placeholder for this input let’s say equal to search just a custom text you can say now what will be the value this is something very important that what value we want so this do props what is the text which user has written this do filter text and what I want as an event I want an event on change whenever the value will change what I want to call so I want to call this do handle filter text change that’s it so my input is defined I want to Let’s Take A P tag for example in this P tag what I’m going to do is again I’m to take a input type now this time it will be of type checkbox because in this example you see I have a requirement of implementing a text box and then I want to implement a checkbox okay so I will say that this is is of type checkbox checked I will check whether it is checked or not so I will say checked equal to this do DRS do in stock only whether it is in stock or not and on change if there will be a change even on change I want to call this dot handle in stock change so that’s it and once this is done I want to let’s say for example give some space and I want to write some text that only show products in stock just after the check box just like in this example in this particular example you can see in the requirement that I want to show some static text that only show products in the stock so I have written only show products in the stock so that is how it completes the search bar component so we have written the two components as of now and now I’m going to write the product table component now this component is again very important because in this component we are going to Define two sub components more so this is our third component which I’m going to write and after that in this particular component I’m going to call two small small sub components so let me Define those components very quickly what will happen you will understand what we are doing so what I’m doing is that I will Define a very small components for example let’s say product category R so I will say product category row extends from react do component this will be my one sub component for this product table component and another would be class product row this will be again a component so extends from react do component that’s it so we have to Define these three components and our example or this complete project reactjs application will be over so what I’m going to do is first I will Define this product table so render method which is implementation of the class and in this render method what I’m going to do is that I will say Define some constants so what is the filter text filter text is this do props do filter text and I’m going to define the stock value with inst stock only which will be this do props do in stock only once this is done I’m going to Define an array of the rows so array of the rows for example I will Define with cons rows equal to an array I’ve defined an array and let’s say want Define the last category so that I have that how many categories are there let’s define it null as of now now what I’m saying that this do props dot products because products I’m passing it as a prop and it is can say Jason array so I can apply for each over here what I’m saying for each because on a array you can apply the for each so in this case I’m applying the for each and I’m on which quantity I want to apply the for each I want to apply on a variable let’s say for example product and want to apply a arrow function that’s it and I will write some conditions over here that index of filter text whether it’s in stock or not and so on I will write some of the values over here I will create a structure and before that what I can do is that I can Define this product category row so let’s define this product category row so I’m saying render now in this render method I’m defining a constant that is category is equal to this do props do category and there will be a return statement for this now in this return statement I’m just using a TR structure for example and this TR I’m defining a header with a th and let’s say some call span I can give some call span yes I can define a call span and what I’m saying is that in this th that is the table head I want to define the category so you can see here that this category is defined as a sporting goods or Electronics so I want to Define n as header that kind of functionality I I want to implement so this product category we have already defined where we are displaying the category now comes the product row now in this product row what we are going to Define so in this product row what all I want is that I want the product maybe the product name whether the product stocked or not at the same time I want the price the product price so what I will say that I want the product name I want the product price okay so let me do this and let me show you the example now so we have defined the product category and product row now you can see over here the product table we were writing the product table where product. name. index of elex equal to equal to minus one we are just comparing whether it is in the stock or not if it is there in the stock we are pushing it to the rows array so you can see here different different rows so we are pushing the values in the rows and then we are are declaring two subcomponents product category row and product Row in which we have defined the category which will be the category header and then we have Define the product row individual where we are saying that we are using the product name and then we are also displaying the product price as you can see in this example that you have to define the product name and you have to define the product price okay so this completes our demo of using the search example let me save this and open it on this screen okay npm start is this is running so just a minute the app.js I have nothing in the index.js I have the search example and in the react dom. render I’m calling this root everything is in place should show up now me refresh it okay now it is showing up so this is the output of this particular example we have implemented the five components as shown in this particular example so let’s check the output now let’s say if I want to search for football it is giving me the result for football only correct and now if I want to remove this football from the search component it is showing me all the results or you can say all the products with their prices if I check this checkbox which is only show products in stock and the products which are in trade are not in stock so it will hide those products which are not in stock for me and if I uncheck this cheick box it is showing me all the products whether they are in stock or not so this is you can say a demo which I have shown you of the complete reactjs fundamentals where you have used state where we have used props we have created the components five components we have created so for example let’s search Nexus 7 which is in another category it is giving me the result of Nexus 7 along with the product name and the product price so that is how we can create a very beautiful applications in reactjs by decomposing the complete UI into different different components this is the beauty of reactjs you can say okay so now we will finally talk about the final reactjs fundamental that is keys so what are keys in reactjs so let’s talk about the keys now so if I talk about keys keys are the elements you can say which helps react to identify the components uniquely so for example if I I have a ordered list where I have some allies I have a unordered list UL where I have some of the Allies so I can Define the keys on them so that those react elements can be identified very much uniquely so basically I can say that keys are the elements which helps react to identify the components uniquely so on the screen you can see that I have two react Elements which is having two render methods but they uniquely identified by different different keys so for one of them I am using the key as 101 um for another I am using the key as 102 so you can say that keys are the basically things which helps us to identify the components uniquely now you can see here that if any of the key is changed again I can check which key has been changed so Keys again I’ll repeat that these are the elements only which are applied on react elements specifically and they help react to identify the components uniquely okay so we’ll see the example of keys now that how we can use keys in react applications this is a example where I have used the concept of keys just to let you understand that how we can use the keys in reactjs and how they help us to uniquely identify the components and react J so in this particular example you can see that there is an array I have created const numbers uh number array with five values 1 2 3 4 5 starting from the index zero obviously because it’s an array now react dom. render this is the first method which is called in this a component is called which is the number list so number list is a component and then there are props which is used called numbers and this numbers will have this array values and then document. get element by ID now let’s talk about this number list component now this is a function based component so function number list now as you can see over here that I don’t need any state I don’t need any Constructor that’s why I have no event which is getting binded that’s why no Constructor no super keyword is used so in the function component that is number list this props is passed so numbers is props do numbers because this numbers will be taken in the props Now list items numbers do map again map is a very important you can say function when it comes to array or to iterate on the array values please remember you can use the map function this is a predefined function in jQuery and JavaScript used for arrays where you can I trate through the different value of the arrays so numbers. map number is just a key you can say now list item Now list item is again a subcomponent here I am using the key which is number. two string so I will have the key as 1 2 3 4 or five and value equal to number now in the function list item what I want to return is I want to return a list of allies having the props do value so whatever will be the value in the number that will be shown as Li but all these will be identified uniquely so if I go to inspect element I’m just showing you that how you can see here so this is a ul and this is the Ali structure which you can see over here so all these Alli structure is defined or you can say identified uniquely with this key value so what will be the key value in this case that key value will be 1 2 3 4 or five okay so that is how we can Define the key on the component or in fact you can also Define the keys directly on you can say the HTML tag for example lii so one more example if you’ll see for the keys the same example which I have shown but in this case just is a very important thing to understand that when you are returning you are returning a ul and and then you are returning the list items from the list item component this is very important to understand over here that how you are returning this ul and Alli structure in the output on the right hand side you can see the output the important thing is that we have created here two function components two function components are one is the number list which is the main component called from react dom. render and in this number list I am calling another sub child or sub component which is again a function component called function list item so function list item I’m passing the props I’m returning the Ali structure from here and I’m also returning a UL structure from where the list items will be shown so what are the list item will be shown whatever the number which are there in my array which is 1 2 3 4 and 5 so all these numbers will be shown on the screen as 1 2 3 4 5 so let’s come back to the PPT again so we talked about keys so basically we have talked about now all the reactjs fundamentals I will just again repeat very quickly for you that what all fundamentals we have talked about we talked about jsx components props State life cycle events refs and finally we talked about keys so these are all the basic fundamentals of reactjs and we have seen very good demos based on these topics one last example or you can say final demo based on these Concepts and specifically on life cycle methods which I want to show you I’m going to show you that and then we’ll start with the advanced concept of reactjs that is flux and Redux so I’ll talk about what is flux and what is Redux in detail but before that let me show you a very good example where we will be using the life cycle methods and I will show you how we can use a life cycle methods while working with reactjs so again I’ve have came back to the same example okay so what I’m doing here is I’m just commenting this particular code so that there is no confusion let’s check the output it should show us nothing now okay that’s great it’s blank because we have not return anything we have commented the complete code okay great so let’s write a fresh code now so what I’m going to do is that I’m going to show you a clock example which will completely show you the date and time but here I’m going to use the life cycle methods which I’ve shown you in the different phases so one of those methods I’m going to use is component did Mount and component will Mount okay so let’s get started I’m creating a component so I’m writing class clock extends from react. component just like we are writing every time but before completing this class component I want to write which is going to rendered on the browser or on the Dom so react dom. render what I want to show I’m I want to show this clock component so component should be always in the cly braces and then I have document. get element by ID where I want to render the output so this is done so we are sure that the first component or the parent component which will be called is the clock component that’s why I haveed the react dom. render in the first place so first thing first so since this is a class component I need to have a Constructor and then in the Constructor I want to define the super keyword so that this do props does not become undefined and then if I want to set the initial state so I have to set it in the Constructor itself so I’m saying this. State this is my initial state which I’m setting so I’m saying what is the date so I’m saying it let’s say new date so I’ve defined the Constructor now outside the Constructor what I’m going to do is that I’m going to Define a method called let’s say tick which is going to work as a ticker nothing else so in this tick I’m going to set the state so I will say this dot set State and what I’m going to set the same state of the same property date with the new date so I have set the state now in the Teck method we’ll call the Teck method later and now I’m going to Define two life cycle methods first of them is component did Mount so intellisense is helping me over here component did Mount and next I want to call is component will unmount so again intelligence I can use the intelligence great so in the component did Mount what we are going to do is that we will Define a property let’s say this dot for example timer ID equal to I’m going to define a predefined method called set interval in this set interval what I want to set is I want to Define Arrow function and that Arrow function is let’s say this dot take and I have to define the range for set interval now in component will unmount since I have to unmount the component I have to destroy the component from the dop I will write clear interval again a predefined one and in this I’m going to to pass this do timer ID so that is how we can Define the life cycle methods now once these life cycle methods have been defined what I’m going to do is default method which needs to be implemented as a part of the class is render in this render I will implement this return statement okay now in this return statement what I’m going to write is that let’s say let’s have a container so Dev is my container I will write some H1 statement example let’s say edura reactjs full course by the chin and then in H2 h2 tag another tag I want to take in the h2 tag what I will write that it is maybe with the time probably I want to say this dot state do date maybe I want to convert it probably to local time string so I and convert it to local time string and I can Place full stop also over here so you can see the output that it is showing the output adura reactjs full course by VJ it is 1129 and 50 p.m. so that is how you can use the life cycle methods in reactjs application and we have set the interval with 1 second so that’s why every time you can say the seconds value are getting changed so I will again repeat this that what I have done in this what I have done in this is that I have set the clock component in the clock component this is my parent component and since this is the parent component what I have done is that I have set the initial State and in the tech method I have set the final State now in the component did Mount and component will Mount methods there are two methods which I have defined component will unmount and component did Mount in these two methods I have said the interval that every second it should show me the the time interval what is the current time interval and in the render method in the return statement I have placed this H1 and H2 tags so now let’s come to the another concept which is flux what is flux in reactjs so let’s talk about something called flux now so till here let me repeat once again that we have completed all the eight reactjs fundamentals which includes jsx props component State and so on we have also talked about some life cycle methods how to use refs how to use keys in reactjs now what is flux now the question which will be coming in your mind is that what is flux so flux is a pattern for managing the data flow in your application as simple as that so what I can say is that there are data patterns through which you can manage the data flow in your application flux is one of them so the most important concept of reactjs or you can say in data flow that in reactjs the data flow is unidirectional by that what I mean is that data flow only in One Direction so that is the use of flux before Deep dive into this flux I want to show you one website from where you can study if you want to go deep dive into flux this is a Facebook site facebook. github.io flux this is a very good site to learn flux starting from the basics to the advanced part so I will recommend that you go through this site facebook. github.io flux this is official site from the Facebook on the GitHub okay so again coming to the PPT so we talked about flux flux is a pattern for managing data flows in your application and the most important concept is that data flows only in One Direction now what are the different parts or what are the different components in flux so flux has basically four main components one is the dispatcher another is a store another is action and the view so we will see this in detail but before that this diagram is very important this is a representation of a data flow in any reactjs application it starts from view you can see the view over here now what view is doing that view sends action to the dispatcher now dispatcher can have n number of actions n number of actions can work on a single dispatcher now the dispatcher sends actions to every store so what happens that once actions are given to the dispatcher from the view now dispatcher sends these actions to the store and then again store sends data to the view so you can see that this is a unidirectional flow of data in reactjs which starts from view through actions it goes to dispatcher and from dispatcher it again goes to store and from store the output again goes to view and that is how it works in a unidirectional fashion now we will talk about all these different components of a flux data flow one by one now what is dispatcher now as you can see in this diagram that dispatcher is getting acted upon by the actions so view is sending a action to the dispatcher so dispatcher receives action and dispatches them to stores that have registered with the dispatcher now every store will receive an action there should be only one Singleton dispatcher in each application this is very important that in any reactjs application there should be only one single dispatcher let me explain you through an example so for example user types in a title for a to-do and hits enter so we are talking about a to-do application over here implemented in flux and Redux for example now what happens is that user types in title for too and then press enter what happens next The View captures this event and dispatches and add Todo action containing the title of the too so in the title you must must have written some too that I have to Dost this task this task and this task that becomes the title of the Todo so what happens is that the view which is there in your unidirectional data flow it captures this event and dispatches a to-do action or any kind of action containing the title of the too and then when it dispatches any action it is received by a store so every store will then receive this action please remember I’m saying here every store and this will come out as a basic difference between the flux and Redux so when we will talk about Redux then we will see that Redux always have a single store but in case of flux flux can have many stores so that is why it is written on the screen that every store will then receive this action so there could be multiple store in a flux base application now what is a store we are talking about store and store so what is a store all about so store is is the place what it holds the data of an application this is the most important thing of any Redux based application in reactjs the store will register within application dispatcher so the store is getting the dispatched action from the dispatcher as an input or you can say the action is received as an input now the data in a store must only be mutated by responding to an action there should not be any public Setters on a store only Getters so action store is getting an action via a dispatcher and then store decides what actions they want to respond to every time I store data changes it must emit a change event so store then do some processing and then it decide that which actions needs to be responded to and every time a store data changes it must emit a change event there could be or there should be many stores in any application when it comes to flux but when we will study Redux please remember there is only a single source of Truth in Redux application so there should be only one store when it comes to Redux and then we can see the same example which we were talking about a to-do application so a store receives a to-do action via dispatcher now it decided it is relevant and adds the to-do to the list of things that needs to be done today and then the store update its data and then emits a change event now what are actions in any flux application we are talking about actions actions are given to store via a dispatcher dispatcher dispatches the action to the store now what are actions so basically action defines the internal API of your application what action needs to be taken they capture the way in which anything might interact with your application they are the simple objects that have a type field and some data but when it comes to action it’s very important to understand that action should be semantic and descriptive when it is taking place they should not describe the implementation detail of that action so I will say that use delete user rather than breaking it up into delete user ID clear user data and so on so remember that all the store will receive the action and they can know that they need to clear the data or refresh credential by handling the same delete user action so instead of longing the names of the action you can be very precise while giving any action to the store now this is just a action example so when a user clicks let’s say delete on a comp completed to-do a single delete to-do action is dispatched because in a to-do application some of the tasks could be completed and some are pending so when you click or when any user clicks the delete on a completed to-do a single delete to-do action is dispatched to the store now what are views so we talked about dispatcher we talked about store we talked about actions now the last thing which we want to talk about is the flux in the flux is views so this is the last component you can say of any flux data flow data from the store is displayed in views so views are the thing which is displayed on or render on the browser on the Dom views can use whatever framework you want in most example we are using the react so when a view uses data from a store it must also subscribe to change events from that store so if you remember the diagram which I showed you from view via action it goes to dispatcher from dispatcher it goes to store and from store it again goes to view so when a view uses the data from a store because in a store something has been updated something has been modified so when a view uses the data from a store it must also subscribe to change events from that store this is very important and then when the store emits a change the view can get the new data and rerender it because it has become the updated data now or the processed data so that’s why we are calling that now from from the store when the data will flow it will be the new data and which is going to be rendered so if a component ever uses a store and does not subscribe to it then there is likely a sub bug waiting to be found actions are typically dispatched from views as the user interacts with the parts of the application interface so please remember whenever there is a user interaction on The View so some actions will go to dispatcher which are dispatched to store and there will be some processing happening some changes happening in the store which is again mve to The View and the views will have then the new data which they can reenter on the browser okay so now we will talk about what is Redux in reactjs because we have already talked about that what is the flux and what are its basic concepts so let’s talk about Redux now so why we have to use Redux with reactjs as we know that react is only a view part in uh MVC model kind of application so to control the data flow we use Redux as a data flow architecture so on the left hand side you can see that there is a application having multiple components which we talked
about and if we want to flow the data in this particular application we want Redux this is the basic use of Redux you can [Music] say so routing is the ability to move different parts of an application when a user enters a URL or clicks an element like link button icon image Etc within the application routing is basically required in transitioning from one view to another in an application in simple words I can say routing is a process in which a user is directed to different pages based on their action or request now we are good to go to understand react router react router is a standard library system built on top of the react and used to create routing in the react application using react router package it provides the synchronous URL on the browser with data that will be displayed on the web page it maintains the standard structure and behavior of the application and mainly used for developing single page web applications it enables the navigation among views of various components in a react application allows changing the browser URL and keeps a UI in sync with the URL reactjs router is mainly used for veloping single page web applications and it is used to define multiple roots in the application when a user types a specific URL into the browser and if this URL path matches any route inside the router file the user will be redirected to that particular room react router plays an important role to display multiple views in a single page application and without react router it is not possible to display multiple views in react applications most of the social media websites like Facebook Instagram Twitter Airbnb Etc uses react router for rendering multiple views to make use of react router we have something called as react router Dom what is this react router Dom which is actually the react router data object model it contains the Dom bindings for react routers in other words the router components for our websites and if we talk about react router native it contains the react native bindings for react router now moving ahead let’s see the advantages of react router because of which we are using react router so in react router it is not necessary to set the browser history manually and Link is used to navigate the internal links in the application it is similar to the Anchor tag which we know is very simple as we have learned in HTML it uses switch feature for entering and the router needs only a single child element so no complexity at all and in react router every component is specified in now talking about the installation part so what we can do is we can just go to our nodes official website and we can just download the nodejs whatever the configurations of your windows are we can just download it and once we have set up our nodejs on our PC what we’ll do is we will just install create react app okay that will be very helpful while creating the application the demo which I’m going to show you in the later part of the video in that it will be very helpful the command to install create react app is npm install hyphen G then create hyphen react hyphen app I’ll just click on this and this is how it is going to install create react app it will take quite some time but I already have it installed so I do not need it so I’ll just stop this thing over here and after that when we will start off with our demo part we will execute one more command that will be npx create react app and we’ll give the application name that we will see in later part part of the video and we’ll start off with the demo part while creating the application itself so this is what you have to do then you will have to go to the directory where you have created the application the folders so with this we have successfully installed our create react application which will help you to directly create and react application we can just add the components to that we can change the code and we can just modify it and we’ll be good to go now let’s discuss the components of a react router so there are four major components of react router which are frequently or always used whenever we are working with the react router so the first one is browser router then we have root then we have link and then we have switch so talking about browser router browser router is a router implementation that uses the HTML 5 history API which includes push State replace State and the pop State event to keep our UI in sync with the URL and it is the parent component that is used to store all of the the other components moving to root so root is the conditionally shown component that renders some user interface when its path matches the current URL talking about the link so link component is used to create links to different roots and Implement navigation around the application and it works like html’s enor tag and talking about the switch so switch component is used to render only the first route that matches the location rather than rendering all matching roots although there is no defining functionality of switch tag in our application because none of the link parts are ever going to coincide but let’s say we have a root that there is no exact in here and then all the root tags are going to be processed with which is start with slashes this is where we need switch a statement to process only one of the statements so this we will see by a demo so now I’ll just open my vs code the editor which I am using you can use whichever editor you want to use and then we’ll see how to include these components of react router on the basis of the part of URL that the router will use to track the content that the user is trying to view react router provides three different kinds of routers now we will see the types of react routers so they are namely memory router browser router and hash router talking about the memory router memory router keeps the URL changes in memory not in the user browsers keeps the history of the URL in memory and does not read or write to the address bar so the user cannot use the browser’s back button Buton as well as the forward button it doesn’t change the url in our browser it is very useful for testing and non-browser environments like react native talking about browser router it uses HTML 5 history API which includes push a state replace State and pop state apis to keep our UI in sync with the URL and Roots as normal URL in the browser and assumes that the server is handling all the request URL and points to root index.html it accepts Force refresh props to support Legacy browsers which doesn’t support HTML 5 push State apis and talking about this hash router so hash router uses client side hash routing it uses the hash portion of the URL that is window. location. to keep our UI in sync with the URL and hash portion of the URL won’t be handled by the server the server will always send the index.html for every request and ignore the hash value it doesn’t need any configuration in the server to handle roots and it is used to support Legacy browsers which usually don’t support HTML push State API and it is very useful for the Legacy browsers or we don’t have a server logic to handle the client s and this route isn’t recommended to be used by the react router dting and the Syntax for these kinds of router we will see just in the import statements we just have to change it and we will elas it as router let me just show you now what we will do is we will set up our react application so we’ll create a react application using Create react app and for that let me just go to my command prompt there let me just go to the desktop so I’ll change the directory over here I’ll move to desktop and then I’ll run this command npx create hyphen react hyphen app and let me call this app as edira routing now this command will create so now here you can see is we cannot create a project name _ routing because of the npm naming restrictions name can no longer contain capital letters so we’ll just give it as Eda routing now here you can see creating a new react app in this folder okay inside the desktop we’ll be getting folder for react application that will be known as Eda routing and it will take some time it will actually take sometime like around 2 3 minutes and once this will be done then what we’ll do we’ll move to our this application folder that is AA routing and then we will install our react router Dom which I had explained you it contains the Dom bindings for react application we’ll make use of npm and we’ll install react router Dom and then we’ll start adding the components I’m using the visual code Visual Studio code AS editor you can make use of any other editors as well now as you can see the dependencies have been installed and you can see over here as well like some 29 packages have been added so with this create react app we can simply create our react application and we can just add the codes we can add the components and we’ll have our react application created with this we have successfully created our react application and the name of our react application we have given as a Rea routing okay as we are going to learn routing with this so with this you can see over here happy hacking and now we are good to go now what I will do is first we will move to the project directory or the application directory which we have created right now we’ll give CD and edore routing and now what we’ll do is we will install the react router Dom for our this application so we’ll give npm install react router D okay router D and we will give a space and hyen save this command we have to give all right this will install our react router Dom for our existing application which we have just now created with the help of create react app it will also take some time but less than the previous one and yes with this we have successfully installed our react router Dom for our our Eda routing application now what we’ll do is now we will start creating or adding the components to the application now what we’ll do is I’ll just close this up and in my vs code I’ll open the folder which has my application so in this yeah in desktop you can see Eda routing is there I will just open this one now here you can see our application or the main folder is edore routing then here we have node modules all these libraries and the pendencies are here like you can see Babel and all for es6 and all we have just for testing so all these are available they have been automatically added with the help of create react app and then here in this public we can see here is the index.html so if we want to change the title or the HTML part of our application we can just make changes over here or we can just create the new one we can just create a whole new code as well so I’m not going to all this HTML and CSS part majorly because we are here to learn about routing first what we’ll do is we’ll go to our SRC folder and here you can see we have app.js file so this component this is actually where we will be using routers react routers we are going to make use of them over here in this application so that we’ll provide the links and the switch and everything which will be linking to the other components so what we’ll do is first of all let me just remove whole code because this is a default one this create react app is for the default one it is like reacts default application which has been created now we have to create the components add them with the help of routers and all now first what we’ll do is we’ll import our router so what we’ll do is we’ll write import so as we have learned about the routers so we’ll give browser router as we have seen this is the first component of react router so we’ll give browser router and we’ll alas as router then we have the other component that is root then we have link and then we have switch and this we have to get from react router Dom now here be clear with the thing that here this browser router is elas as router now to use react router what we’ll do is we’ll create some components in this react application so what we’ll do is inside our this SRC folder what we’ll do is we will create one more folder and that we will make it as comp component so we have one more folder inside the SRC that is component now here in this we’ll create other files other JS files which are actually the components so let me just add one file as home.js then we will create one more about. JS and then we have contact. Js so these three components I have added now let’s add some code to this so that will be available on the screen whenever we will be executing our application so let me just go to home and let’s add some code like first thing is we have to import react from react and then we will write the function or the reducer we know function home which return heading we’ll write like welcome to Eda and that’s it and then we’ll close this function and we’ll write this export default app default we’ll just save it and then next is our about component so in this will’ll simply let me just copy it from here we’ll just paste it and we’ll make the changes over here here is about now let me write let me write something about Eda so Eda is in e-learning platform and let me give you some more thing like like know more about Eda here now here we I’ll make use of the anchor tag and I’ll give the link [Music] http://www.ed now here we have the link and I want to display this as well so what I’ll do is I’ll just type it over here as well and with this we have closed our anchor tag now when we have created this one and the anchor tag is closed over here now one more thing is we have to return something so here in return I’ll put all this inside a div so this one is also ready and here I’ll have to give this about the function which we have just now created let’s save it and now moving to our contact component so again let me just copy this thing and we’ll put it here now here what I’ll write is like for queries contact here now no link I don’t want to give any link over here now let’s just put the number let me just put this over here and one more thing see and if I want to put it in the next line and all so I can just give the BR tag as we know in HTML and no need to give it like this let me give one more yeah now in this about what we’ll give is we’ll give the in place of about we’ll give contact me just remove this anchor tag now let’s make a little change over here let me just put it inside the address so that it will be like a single element over here and let’s just remove this heading tag all right and we’ll just give it up so we have created three components and we have added them the home component then the about component then we have our contact component now in this app.js what we’ll do is we will make use of our react router and then we will link these components now what we will do is we will start adding the components to our app.js the components of react router over here now as we have already added this browser router as router now let me just create class app extend component and then we’ll give it as render we’ll make use of render function then we’ll return router and inside a div we provide the class name let’s give it as app and then we have closing tag for rter now moving ahead what we have to do is inside the div we have to put the links as well link is also one of the component of react router before moving ahead we can just see let me explain you the components which we have created especially talking about the props associated with the root component we’ll see over here as you can see the exact right this this is used to match the exact value with the URL for example here we have given exact and then the path that to home component and this will only render the component if it exactly matches the path if we remove exact from the syntax then UI will still be rendered even if the structure is like slash and home like that and then we have something called as path over here so this specifies a path name we assigned to our component the path name which we have assigned like contact home about like that and then we have something called as component it refers to the component which will render on matching the path these components which we already have contact home about out all these and as we have seen in this we have switch as well this switch will be used to render a single component wrap all the roots inside the switch component so we have just wrapped it around and this link we have used to create the links to our components it uses the two prop to describe the location where the link should navigate so here you can see this two prop this two prop has been used by this link component now let’s see the output of this application or this code which we have written now we will see the UI of our application it’s taking a little time so it will get executed browser will be launched here so you can see over here on Local Host 3,000 it will be launched here it comes now this is the page okay now whenever I’ll click on home now we have moved to our homepage this is happening with the help of our router the components which we have used the link component we had made use of browser router and the switch now when I click on about us here you can see the URL is also changing and with this if I’ll click on this link so this is the normal HTML link part with the help of anchor tag I have just redirected to our Eda homepage let’s just go back and then on contact us you can find it over here so whatever we wanted to display in our application that’s been displayed in the different pages and we are redirecting to these pages with the help of react router and here is the URL and the application name is like react app we can make change in that also let me just go to this one and in the index.html we can just change the name of the title like we can change the title let me just give it so here I’ve just made it as Eda let me just save it and then it will automatically be reloaded here you can see now the name of the application is your Ed over here so this is the output which we are getting so this is how finally we have successfully implemented the navigation in our react app application using the react router now as earlier we have talked about the types of react router so let me just show you here so as you can see in this app.js we had made use of browser router so we have hash router and memory router what we have to do is just in place of this browser router we can just simply put memory router and everything else will be same and we can just elas it as router similarly for hash router we just have to make change in hash in place of memory I have kept it as hash now it became hash router and the functionalities which are supported by hash router memory router and the browser router will automatically be implemented so no need to change anything else we just have to import that type of router and we will elas it as router itself and we have already discussed what are the functionalities and how these routers are implemented according to their [Music] types now let us go and explore all about reacts hooks starting from what is reactjs hooks reactjs hooks are functions that allow you to use the state and other react features in functional components they were actually introduced in react 16.8 has a way to make it easier to share the stateful logic between the components and also to make it easier to work with the functional components here the most commonly used hooks are the use State use effect and use content so these are considered more important or most useful hooks so other than this we will also explore some of the additional hooks too for example use reducer use memo use call back and use layout effect so these are the hooks that we will be exploring in this session we will see each of it in a detail form right now before that we will see what actually the hooks are now let us go back and see before react h hooks so before react hooks if you wanted to use the state or other features in the component then you had to use a class component here the class component are more complex than the functional components and can make it difficult to reuse the stateful logic here with the react hook you can use the state and other features in the functional component which makes it easier to share the state full logic between the components and also it makes it easy iier to work with the functional components here the react hooks differ from the traditional react class component because in that they allow you to use the state and other features in the functional components instead of having to use the class components and additionally you must keep this in mind here the react hooks do not require the use of this keyword which makes them less verbos and easier to understand and why do we say here the class component is more difficult so here the class component in react are based on this JavaScript class syntax which can make them difficult to understand for the developers who are new to the react or who are more familiar with the functional programming additionally these class components often include the boiler plate code such as the Constructor functions and binding the methods to the correct context which can can add unnecessary complexity and make the code harder to maintain and the most important feature of this react Hook is it allows the creation of custom hooks which are reusable functions that can hold the state or the logic that can be shared between the multiple components here this makes it easy to extract and reuse the logic that is used in the multiple components so at the end this can make the code base more maintainable and easier to understand one of the main advantages of react Hook is that they make it easier to share the stateful logic between the components as I said in the previous statement so this is because the state and the logic can be extracted into a single hook and it can be reused in multiple components rather than having to duplicate the logic in multiple class components react hook also make it easier to test the functional components since they do not relay on this keyword and the life cycle methods now let us see the types of hooks we have in this session here we have three major hooks that is use State use effect and use context so these are considered to be basic Hooks and more important hooks or commonly used Hooks and additionally we will also look into use reducer use memo use call back and finally use layout effect so these are the hooks which we will be covering in this session other than this we also have many other hooks so if you want to learn more about hooks or more about react years you can enroll to our edura react years certification training course where we will be providing you with an Hands-On and a live demo sessions so here we will get started with our first hook that is use state so let us see what is use State and how does it work in our course code and I will give some of the tips that how can you use the use State inside the code now according to the definition use state is a hook in react that allows you to add the state to the functional component state is a way of storing and managing the data that can change over time and can affect the components behavior and rendering though I will explain it in a detail form here this U state is a hook in react that allows you to manage the state in the functional component prior to the introduction of HS the State Management in react was only possible in class-based components so with this use of use State you can now manage the state in the functional component as well and also the U state is a function that takes a single argument so which is the initial state after that it returns an array with two elements that is current state and a set a function for updating the state the current state is a value of the state and the setup function is used to update the state so here I will explain this in a detail form with an example so I’m using visual studio code so here I will show you a small demo for that I will jump into Visual Studio code now as you can see I have already created a app called counter app so you can see here the counter app and here I have created a counter. GSX inside the source folder and inside the components folder now let us write a small react hook example first I will import the react component from react for that write just import react from react okay after that I will import UST State Hook from the react package after this line for that you just need to write Import in the bracket U state so you will have some of the recommendations over here and you need to find U State over here so State and you can notice that I’m writing in a camel case statement here the react GS takes the input in a camel case after this now that we have imported the component and use state from react at the same time we need to export this file file to the index.js right so that the output will be shown in the browser so that don’t forget to export this file to the index.js so I will export so just type export default counter because my file name is counter so I’m writing counter and you just need to go inside the index.js and include the counter file inside the react strict mode now let us get back to the counter. JS file so now let us declare a new state variable so let us call this as count here the U State returns a pair of value that is the current state and the function that updates it as I said in the explanation so that we will just write a function called counter inside that just write const and pass the values that that is the current state and the function that updates it right so here the current state is this count and then we will set the count so this will be the function that updates it and in our component we use the U State Hook by invoking it and passing the initial value for our state variable which is zero so I’ll use that so I’m using the use state so I’m passing the value as Z zero okay now let us return this so I’m wrapping this with a div tag now here we use the count variable to display the current number of Clicks in the page and in the button tag here we use this onclick property to specify a function that will be called when the button is Click right now for that I will write a paragraph to indicate the numbers so I’m writing you click here I’m calling the count and this count will be indicated in numbers so you have clicked this many times so right so so I will give the button to click so on click so I’ll set I’m calling this set function so that is set count this s should be in the small here the function that we pass to on click is an arrow function that calls the set count and passes in the new value of the count so which is the current value + one so let us write the count that is the current value and + one so whenever the button is clicked here the count will be incremented like the current value + one so the count will be incremented to one so I’ll close the button by telling click okay so let us run this by typing npm start and you can see the server has started you can see that we have written you clicked this many times right so let us click this button and check so here you can see the number is incrementing so if I click on this the number is changed the value to two so that the current value is right now is two so if I click the button once again the number will be incremented + one so that the current value + one will be incremented so here as you can see the count this is the current value and plus one so every time the button is clicked this function will be called and the state variable count will be updated and here the component will be rerender to reflect the new value so I hope you understood now I will give you some of the tips to use the use State here we have some of the limitations for example keep State update simple here you need to avoid the complex Logics or the calculations when updating the state instead use a call back function to update the state based on its current value and next so you need to keep in mind that you need to use the use State when it is only necessary here use props or the context when possible instead of creating the state for every piece of data after that you need to use the use effect hook for the side effects keep the state top level that means you need to keep the state at the top level of your component hierarchy as opposed to bury deeply in class component this make it easier to understand and debug the code easier and you need to keep in mind that you need to test your component always you need to test your component to make sure that they work correctly and the State updates are behaving as expected with that we will move on to the next hope that is use effect now let us explore about use effect here this use effect is a hook in react that allows you to synchronize a components with an external system also it will allow you to tell that react to run a piece of code after rendering in order to update the system or the side effects of the component so this is done by specifying a call back function that contains the code to run and an array of dependencies which are variable La that components uses and that react will watch for changes now when the component is first rendered the call back function passes to the use effect will be run this is similar to the component did Mount life cycle method in the class component if any of the dependencies specified in the dependency array change react will rerun the effect now this is also similar to the component did update life cycle method in the class component so as I said before here we have class did Mount class did update and class did unmount so these life cycle methods are used in the class component so here the next life cycle I’ll be explaining is component will unmount here when the component is unmount the cleanup function pass to the use effect when it will be run this is for cancelling Network request or cleaning up any other side effects that we created now that we will understand this use effect hook with a small example so I’ll go back to the visual studio code I will clean up the use State I will keep the react component and the export has default now we need to use the use State and use effect from the react so for that we will import use effect along with the use state from the react react package after the react component line so that I will just import inside the curly braces right use F and use state right in our component we declare a state variable data using this new state and and the initial value is an empty array so for that we will just write a function for that counter so for that I will be setting the constant values here and I’ll pass both width and the set width as I said the current value and the function that will be updated so here withd is the current value and I’ll set the state so now what does this line mean so here I have written this line right now this means that I’m taking the windows inner width so let us see for example I want the inner width of the browser and I need to design a web page where my grid needs to match it so I need to know the width of my system or the browser so that I’m taking the inner width of the browser now let us fetch the use effect I’m taking the function handle resize so we need to know the size of our window right so that is why we are using this function function handle now I will set the WID for window inner width here the set with function update this date when the browser window is resized now let us set the window uh event listener here use effect Hook is used to add an event listener to the window that is listens for a resize event and when the resize event is triggered the handle resize function is called for that we are writing a code here so for that window dot add event listener and I’m specifying here resize here as I said when the resize is triggered the handle resize will be called to update the width of the state in the new value of the windows inner R now here let us clean up the function to remove the event listener here now I will return here I will return the remove event listener here I’m specifying this window do remove event listener here the empty array at the end of the use effect is the dependencies it means this effect only runs once on the component mode right so here now I will return this also so I’m WR the windows width will be so I’m calling this width function here here the component returns a Dev that displays the current width of the browser right now let us check out the results here the window width is 614 now let us resize this here here as you can see if I resize the windows WID changed to 335 so if I again resize so it will change according to that so it will not change the height so as if we have just set only for the width the total window width of my system is 614 so if I resize so it will change according to the size we moveed to so I hope hope you understood the example with the use effect here some of the tips to practice this use case in a best way for that you need to First understand the purpose of the use case of the use effect hook here it is used to handle the side effects so as I said in the example such as the data fetching in a functional component and always you need to include a dependency array as the second argument to the use effect and this array should include any variables or state that the effect depends on here if a variable is not included in the dependency array that the effect will run on every render and you should be mindful of the order in which effect runs here this effects are executed in the order that they defined so it is important to consider that the order of your effects if they are dependent on each other and you should use the cleanup function provided by the use effect to remove any side effects before the component is unmount so this is especially important for the data fetching and subscriptions to prevent the memory leaks so as I did here in the example I did the cleanup function to remove the event listener right so like that and also you should keep in mind that the excessive use of use effect can lead to unnecessary re vendors and it can be slowed down your applications and also you can use the use context who instead of use effect when possible here the use context is a simpler and more efficient way to manage the shade State across the multiple components that is what we are looking next we will look into the use context here now let us see what is use context it is a kind of H that is used to consume the context in a functional component it is an alternate to the context type property or the consumer component that we used in the class component here when a component needs to access the context it can use the use contact hoop to describe to the context and retrive its current value the hoop takes the context object has it argument and Returns the current value of the context the component can then use this value to update its state or props the use context hook allows a component to subscribe to changes in context so that it can rerender when the context value changes so this is done without the need to pass props down manually through every level of the componentry which makes the code more efficient and maintainable here when a context value changes the react will re render all the components that are using that context this means that the component using use context hook will be rendered to which is how the component will get updated with the new context value now if I summarize the use context the use context hooks allows the functional component to access the context and the subscribe to changes in context it also eliminates the need to pass the property through the multiple levels of the component Tre eventually which leads to more efficient and maintainable code now let us see a small example so let us go to visual studio code and I will just remove from the function so default let us keep import Rea component from Rea here in import we will just import the create context with use context okay so now let us create a context with a default value for that I’m writing the const and theme context here we use this create context to create a new context called this theme context okay with the default value of light so I’ll keep the default value as light which is equal to create context to light right fine now let us create a function counter now let us use the context to access the current theme right so that I’m specifying the cons now the theme is is we are using the use context in theme context here in our example component we use the use context hook to access the current value of the theme context right so here we have light so we need to access this light in this theme context here we will return the div so let us specify the class name as uh theme right and let me write something like the current so we need to get the uh output from this theme so when the value changes here the value here will be also changed accordingly now here let me write a function called app and return the theme context dot provider value is dark so I’m specifying the counter over here inside the theme context right now let us see the output here as you can see the current theme is light right we access the value of the context in this case here the theme and we use it to set the class name of the div element and in the app component we wrap the element component with the theme context provider and set the value to the dark okay here now whether the value is provided to the context will be available to all the components that are wrapped inside the team context provider and all of them will be able to access the current value of the context by calling the use context and theme context okay now here some of the tips to practice the use context here to keep the context value minimal Only Store the values that are necessary for the components that are consuming the context and you need to avoid the storing unnecessary data as it can lead to unnecessary rerenders and performance issue and also you need to use the default values always provide the default values for the context when creating it in case that consuming the component does not have access to the context now you should use the use context for Global state so that it is shared across the multiple components such as the users authenticated status or the selected theme also you need to avoid using context for local state here use State hooks for local state that is specific to single component rather than using the context only update context when necessary you should only update the context when the value has changed to avoid the unnecessary rerenders and performance issues here you need to use the use effect hop to update the context the next we have the test context test the context value and update to ensure that they are working correctly here we use the test context to test the value that were updated correctly and whether it is working correctly now then we have the use multiple context so here if you have m multiple pieces of global State and that need to be shared here we need to consider using the multiple context to keep the state organized and easy to manage with that we will move on to use reducer who here the use reducer is a hook in react that allows for managing the state within a functional component here it is similar to use state but it is typically used for more complex State Management and the state red rer hook takes two argument a reducer function and a initial State here the reducer function is a pure function that takes the current state and an action and it Returns the next state the initial state is the starting state of the component State a component can call the dispatch function returned by the use reducer to send an action to the reducer here the reducer that updates the state based on the action and the current state and also the component reenders with the new state the use reducer is considered more powerful than us State because it allows for more complex State management such as handling the asynchronous actions and managing the multiple pieces of State at once in short the use reducer is a hook that allows you to manage the state within a functional component in a way that it is similar to how you would manage the state in a Redux store it takes two arguments a reducer function and an initial State as I said initially and Returns the current state and a dispatch function that can be used to update the state now with that let us look into a small example so let me remove from the import again let us import the use reducer package from react after that we create a reducer function that takes in two arguments that is State and action here which are the current state and the action that is being dispatched respectively okay so that let’s write const so initially I’m setting the value to count zero so initial state is count zero fine after that the function the function reducer State action after that I have switch case in that I will write switch I’ll write action type if that is the case then the case should be in increment then I will return the count to the state count + one if the case is in the decrement then I will return count State minus one then default I will return the state first let me write the code and I will be explaining you each and every statement here right so that first here I’ll write the function here as you know the use reducer hook returns a pair of values the currenty State and a function that updates it in our case we use the destructuring assignment to assign the state and dispatch right here we use the state count to display the current count in the page and in the button tag here for that I will specify the page and the button tag here for that I’m returning a statement so return here I’m writing in the count here count and the state count now let us specify the button for increment as well as the decrement here on click let us write the dispatch so this type will be in increment fine now for the same I will give for decrement right see here here I am giving the decrement so after that the div is closed so here the function that passes in the on click property to specify a function that will be called when the button is clicked so I’ll be showing that in the output page here the function that we have passed to on click is an arrow that function calls dispatch and it passes in the object that describes the action that should be performed here in this case the action type is either increment or decrement right so when the component is rendered it was initially the number is zero the count is zero so when the button is click in the increment so it will call the dispatch function with the type increment and the reducer function will receive the action and the state so that it will update the state and increment by one so see for example if I go to the output so if the button is clicked in the increment so the count will be two for example if I increment one so the count will be + one right so when the minus button or the decrement button is clicked so it will call the dispatch function to the decrement then the reducer function will receive the action and the state so it will update the state and decrease by the count one and the component will rerender and it will show us the output as minus1 so count minus1 so here keep your state and the action simple now let me give you some of the tips here you need to keep your state and action simple the use reducer is designed to handle the complex State and actions but it is important to keep them as simple as possible to avoid the confusions and make it easier to debug and also you should use the initial State correctly make sure to provide an initial state that is the same type and shape as the state in your reducer function and the use actions to change the state you need to use the actions to change the state in your reducer so do not modify the state directly as this can lead to unexpected Behavior also you need to keep your reducer function pure so what that your reducer function should be pure means it should not have any side effects and should not relay on any external state or variables so with that we will move on to the use memo use memo is a hoop that allows you to optimize the performance of your react component by only recalculating a value when one of its dependencies has changed now it is similar to the use effect hoop in that it allows you to perform a side effect but instead of updating the component state or props it returns a value that can be used by the component here the use memo hook takes two argument as previous hook sticks the first one is a function that returns the value you want to store and the second one is a array of dependencies the function is only called when one of the dependencies has changed if none of the dependencies have changed the previous value is returned instead of recalculating the value for example if you have an component that displays a list of items and the list is passed in as a prop you can use the use memo to only read ref filter the list when the search item changes instead of ref filtering the list on every render now let us see a small example so now let us go to visual studio code I just have import react component from react and I have exported the counter now let me import the hooks from the react so I’m importing use State and use memo right now let us just Define a functional component called counter okay so function counter now let us create the state variable for first name last name and H so that constant first is our first name then I will set the first name here I will use the use State same thing for last name and H I am giving a empty parameter over here so that it is dynamically updated when the user enters the first name last name and the H okay right now let us calculate the user object over here so now let us see this function will uh run only if the first name last name or the a state variable have changed so I’m giving the uh user also so const user by using the use memo so let us return turn the full name the full name consist of the first name and the last name and finally AG right in the array I’m just giving the first name last name and age return inside the diff I’m just giving the input value for the first name last name and the H here the component also uses the use memo here right so this hook can create a memorized object called the user so that is why we have specified the user over here and that combines the first name last name and the age the state variable into a single object with properties that is first name and the age the components then renders input field that allows the user to update the state variables and display the user object so that is what so here I will be giving the input values over here here first one is the first name on change so if the value is changed then the output should be rendered here in the age we have to type the number so the input value will be in the form of number right then let me give a paragraph inside saying the full name and the h now let us see the output so if I show you the output here I can type my name so here in the full name you will get uh the first name and this is the last name so for example I’ll type V so as you can see the full name I have written in the first name as T and the last name has v so in the code here here it should return in the name of full name is the first name plus the last name and the age right so here if you see uh in the place of first name I have typed only my first name and in the last name and in the place of H since I given in the input has numbers so it will tell you to increment or decrement or else you can even type the number so in place of age you have the number over here right for example 46 yeah and you can increment or decrement as you need so in this code the react functional component is called the counter right so it uses the react hook called use State and use memo to manage and update the component State and to perform a calculation based on the state here the component has three state variabl that is the first name last name and H so which are initialized using the U State now these State variables are used to control the values of three input field rendered in the component jsx that is these three input Fields here the component also has a user variable so here you can see the the user variable right here the function concatenates the first name and the last name the state variable to create the full name the property of the user object and the user age that state variable as the state property the second argument of the use memo is array of dependencies which is used to determine when the calculation should be rerun in this case the calculation will re run only if the first name last name or AG State variable has changed the component reenders and input field from each state variable and displays the full name and age property of the user object right with that we will move on to the tips for use memo use the hook called use memo when you need to compute a value that depends on or state but not change often always pass a function that runs the value you want to memorize has the first argument the function should take the props or state that the value depends on an argument and the use mve with the second argument an array of dependencies to tell that react which values the memorized value depends on so this will ensure that the memorized value is only recalculated when one of the dependency changes avoid using use memo in render functions as it can lead to poor performances instead you can use it in the component functions that are called before the component rerenders also you need to use the use memo with the caution when working with the large data set or the complex computations as it can cause performance issues if not used correctly and avoid using the use memo to store functions as they cannot memorize instead you can use the use callback hook for this purpose now let us see use callback hook use callback is nothing but it is also a react hook that allows you to optimize the performance of your react component by only recreating a callback function when one of its dependencies has changed it is similar to use memo but that allows you to store a value and only update it when the dependencies has changed but instead of storing a computed value it stores a call back function here the call back hook takes two arguments the first one is a call back function that you want to store and the second is a array of dependencies here the function is only recreated when one of the dependencies has changed changed if none of the dependency have changed the previous call back is returned instead of creating a new one for example if you have a component that displays a list of items and the list is passed in as a prop you can use the use call back to only recreate the function that handles the recreating the function on every render but it is important to note that the use call back is often used in the conjunction with the use memo when the dependencies are object or the function to prevent unnecessary rerenders and recalculations as use memo only recalculates the value when the reference to the object or functions changes now let us see a small example for use call back hook and import the hook packages from react that is I’m using the use state and use call back from react now the function called counter let us initialize the count and the increment value here right so that for here I’m writing the const so I’m I’m setting the count as well by use keys by use US state and the next one is increment I’m using the use call back function over here let’s set the count to count + one because we are incrementing it right so right now let us return with a Dev tag inside that I’m writing H1 tag so I’m telling the count value then I’m specifying the child increment after this we have the child increment over here as you can see right so that I’m creating a function over here called child inside that I’m just passing an argument call increment by returning a button with a onclick function increment right now in this example the parent component has a state variable that is count so as you can see here we have count this is the parent component and the call back function is the increment that increments by one so here the count plus one so as you can see this is the parent component plus incrementing by one here the child component receives the increment function as a prop and renders a button when click and it calls the increment function over here the use call back Hook is used to memorize the increment function passing in the count as a dependency this means that the increment function will only be recreated if the count State variables change so this can help to prevent the unnecessary rerenders of the child components when you run the code the output will be a increment button and a H1 tag saying the count is zero so when you click on the button the count will be increasing by one and the H1 tag will be displaying the updated count right so if you can see I’m clicking on increment and the number changes to two by increment + 1 so 1 + 1 is 2 okay so right now let us see some of the tips so here use the use call back when you need to pass a call back function as a prop to a child component and you want to avoid the unnecessary rerenders always you need to provide the dependency array has the second argument to use the call back this tells the react which variables the call back depends on and when it should recreate the call back and also you need to keep in mind that the dependencies you include in the array if you include too much or unnecessary dependencies it can cause the unnecessary rerenders and negatively impact performance and you need to avoid the use call back inside the loops or conditions as it can lead to unexpected behavior and hard to debug the issues and always you need to check if the call back function is the same using the reference equality operator before passing it to a prop so this will prevent the unnecessary rerenders of the parent component you need to be careful while using the use call back function with this the state or prop that are objects or array because these are passed by references not by values so if the call back depends on such variables it will be recreated every time the parent component reenders and you need to be aware that the use call back does not work with async functions because it cannot memorize the results of asynchronized operations always test your component with and without use call back to check that if it works has expected and that the performance improves you expect as visible right okay now let’s move on to the last hook in this session that is use layout effect now what is use layout effect use layout effect is a react ho that allows you to synchronize all layout changes to a component here it is similar to the use effect but it runs synchronously after all Dom mutations now this can be useful when you need to measure a Dom node or read its layout before making changes that affects its size or position also it should be used with caution as it can cause visual inconsistencies if not used correctly and also it is recommended to use use effect unless you have a specific use case that requires the synchronous behavior of use layout effect so you need to be careful while using the used layout effect and also importantly to note that the used layout effect should be used only for updates that are critical to the visual appearances of the component and that cannot wait until the next frame for all other updates it is generally recommended to use the use effect instead with the run asynchronously and does not block the main thread and also so it is important to remember that if you need to perform any side effects that involves the Dom such as adding or removing the event listeners you should do so inside the use layout effect instead of use effect this is because the use effect runs after the browser has painted and may cause unnecessary layer thrashing if it updates the layout of your component okay with that let us move on to the example now this code is a simple react functional component that uses the use layout effect and the use state so here it uses these both hooks to measure the width of an element and display it in the screen okay the first code Imports that the layout effect and the use State and the use ref from the react Library right here the U state is a hook that allows you to add the state to a functional component in this case it is being used to create a state variable called WID and that will store the width of the element here the UST State hook also returns a set width so that can be used to update the value of the width State variable here now the use ref is a hook that allows you to create a reference to a Dom node so in this case it is being used to create a reference to a div element that will be used to measure the width of the element over here here the used layout effect is a hook that allows you to synchronize and apply the layout changes to the component so it is similar to the use effect as I mentioned earlier but it runs synchronized after all Dom mutations so this can be useful when you need to measure a Dom node or read its layout before making changes that affects its size or the position so this component start with the div element with the ID my element and within the WID State variable is displayed and use layout effect is then invoked so inside the hook the code first gets a ref reference to the element with the ID called my element using the document. get element by ID inside the my ID this used layout effect Hook is then invoked inside the hook the code first gets a reference to the element using the ref variable called ref do current you can see here this ref dot current then it uses the get bounding light ring right this method to measure that the width of the element and assign it to the variable width after that the set width function is invoked with the width variable as an argument so which updates the state variable with the width of the element here the used layout effect hook also accepts a cleanup function which is a function that runs when the component is unmounted or the effect is being rerun so this is that function okay so the cleanup function will also display the cleanup in console so when you inspect in the console then you will get to know about it right and also you need to keep in mind that uh it is important to note that the used layout effect hook should be used with the coction as I mentioned so as it can cause the visual inconsistencies if not used correctly so it is recommended to you to use the use effect unless you have a specific use case that requires the synchronized behavior of the use layout effect and it is important that if you don’t provide a dependency array the effect will run on every render so which could lead to a performance issue so it is better to provide a dependency array with the values that the effect rely on so that it only runs when those values changes okay so it should not run whenever the small changes happens the whole program will run so right in this example an empty dependency array so this is the empty dependency array so it is passed to a use layout effect ho so which means that it will only run the code once when the component is first rendered so in this example instead of using the document. getet element by ID to find the element it is passed to a reference to the element as it uses the ref dot current dot here the ref dot current dot get bounding client R so to get the width of the element so let us see the output over here so we have to run so after that so as you can see the width of the element is around 613 Point 44 okay so let us inspect this here you can see as I mentioned you will get a console here we have console right as you can see here the cleaning up function as I said in the program right here you will get the clean up function here so inside the console you will get the cleaning up [Music] we should know why to use Redux react is one of the most popular JavaScript libraries which is used for front-end development it has made the application development easier and faster as it follows the component based approach where the data flows through the components basically react follows unidirectional data flow that is data always flows from parent to child component where child component can never pass data back up to the parent component as you can see on the screen the colored circles are representing the components where the upper component is the parent while lower ones are the child or subcomponents the view cannot interrupt in the data flow so data Flows In unidirectional fashion here data flows from parent to child react does not provide any way for direct component to component communication although react has features to support this approach but it is considered to be a poor practice as it is prone to errors as you can see on the screen a child component can never pass data back up to the parent component and here is the catch so the question comes is how can two non-parent components pass data to each other this is where Redux comes into the picture as you can see in the picture a store is a place where you can store all your application State together now the components can dispatch State changes to the store and not directly to the other components then the components that need the updates about the state changes can subscribe to the store so we can sum up into the points as produx offers a solution of storing all your application state in one place called a store components then dispatch State changes to the store not directly to other components and then the components that need to be aware of State changes can subscribe to the store Redux helps you manage Global state that is actually the state that is needed across many parts of your application Redux separates the application data and business logic into its own container in order to let react manage just the view react gives only the view in MVC model where MVC stands for model view and controller so we can say react is just the view and to control the data flow we use Redux as a data flow architecture as you can see on the screen react is responsible for the view that is the web application on the browser and Redux controls the data flow now let’s understand understand what is Redux Redux is a pattern and library for managing and updating application State using events called
actions Redux separates the application data and business logic into its own container in order to let react manage just the view it’s an application dataflow architecture Redux was created by den abov and Andrew Clark around June 2015 it was inspired by Facebook’s flux and influenced by functional programming language Elm it got popular very quickly because of its Simplicity small size as of 2 KBS and great documentation this is the basic idea behind Redux that a single centralized place to contain the global state in your application and specific patterns to follow when updating that state to make the code predictable so basically the patterns and tools provided by Redux make it easier to understand when where why and how the state in your application is being updated and how your application logic will behave when those changes occur Redux guides you towards writing code that is predictable and testable which helps to give you confidence that your application will work as expected now let’s look at the principles of Redux Redux follows three fundamental principles where the first one is single store or we can say single source of Truth the second principle is state is always read only and the third one is changes are made with pure functions or reducers now let’s understand these principles in detail starting with the first principle that is single store so when I say single store it means that all my applications state are stored in a single immutable store as with only react unidirectional data flow direct communication between components is not allowed now the state of the entire application is stored in an object or state tree within a single store components state is stored in the store and they receive updates from the store itself so components dispatch something to the store and then the other components when they get to know that something has been updated they subscribe to store now let’s move to the second principle that is the state is read only which means the only way to mutate the state is to emit an action which describes the user’s intent hereby muted I mean is to update so we can say that we can change the state by triggering an action which is an object describing what has happened as you can see on the screen here the action is no action and when the action is switch on the bulb is getting lighter now let’s talk about the third principle that is change using only pure functions in Redux pure functions are called as reducers the reducers are used to indicate how the state has been transformed by action the reducers or pure functions take two parameters as input which are the previous state and the action so when it takes the previous state it gives us the new state as you can you can see in the picture the previous state is that the bulb was not on and then it has been worked upon by the reducers and then we get the new state that is the bulb is on now I’m going to talk about the components of Redux Redux has four components action reducer store and view so let’s understand these components in detail starting with the action action of the plain JavaScript objects which are payloads of information for the store so basically the only way to change the state content is by emitting an action as we have already talked about it so here action means plain JavaScript object which are the main source of the information which we use to send data and data could be user interaction internal event like API call or form submission we can send these from the application to the store and then the store receives this information only from the actions and then we have to send the actions to the store by using store. dispatch for example here as you can see we Define the type as ADD too and then we can Define the parameters as Text Now actions are created by action creators some of the points to be considered in actions are that it must have type property that indicates the type of action being performed they must be defined as a string constant and you can add more properties to it now talking about the action Creator action creators are the functions which create actions and they takes in the message converts it into into system understandable format and returns a formatted action object action creators are the normal functions that return the function and to call this action anywhere in the application we can simply use the dispatch function where we can Define dispatch and then we can Define it to do add to do text as a part of dispatch method so here we can add dispatch after action we have reducers basically actions describe the fact that something happened but they don’t specify how the applic State changes in response so here comes the job of reducers reducers are pure functions which specify how the application State changes in response to an action it is based on the error reduced method where it accepts a call back a reducer and let us get a single value out of multiple values so we can Define reducers as pure functions which specify how the application State changes in response to an action some pointers to be considered for reducers are they do not change the value of the input parameter they determine what sort of update needs to be done based on type of the action and returns new values it Returns the previous state if no work needs to be done the root reducer slices up the state based on the state object keys and passes them to their respective specialized reducers reducers don’t manipulate the original state passed to them but make their own copies and then updates them now let’s understand the reducers with the help of a simple example here we have defined whole function reducer with the arguments initial State and action then we can use Simple switch action type in the case at Todo we are returning the object assigned to State and then here we have a to-do list then in text we are going to work on the action. text and then completed should be false that uh is what we are going to return the state itself so here we are taking help of previous state action and new state as part of reducer component we should avoid the following things inside a reducer that mutating its arguments that we should not change the arguments inside a reducer we should not perform side effects like API calls and routing Transitions and we should not call non-pure functions like date. now or math. random now moving on to the star component of Redux that is store store can be defined as an object which brings all the components to work together it calculates the state changes and then notifies the root red us about it so basically store can hold the application State and provide some helper methods to access the state dispatch actions and register listeners so the entire State object tree of an application is saved in a single store here we can pass the middleware to the store to handle processing of data and to keep a log of various actions which can change the state of the source and all the actions return a new state by the reducers here in the example taken we have created a store from Redux where we can import to-do app from the users that we are going to create and then we are going to use the store component as a part of a stores with a store the data State can be synchronized from the server level to the client layer without much difficulty this makes the development of large applications easier and faster store is responsible for holding applications State allowing access to State via get State method registering listeners via subscribed listener allowing the states to be updated via dispatch action and also it handles unregistering of listeners VI the function returned by subscribe listener now let’s talk about the last component view view is nothing but the thing which is displayed on the screen and in formal terms we can say view displays the data provided by the store as you can see in the picture the store provides the data which is displayed as view on the browser screen smart and dump components together build up the view smart components are the managers who are are in charge of the actions and pass down a function via the props to the dump components and dump components provide information to the smart components if any action is required they receive them as props and use them as call back now let’s understand how the components in Redux are set up first of all we have to get the store ready then we have to set up the communication amongst the components and then we have to prepare the action callbacks let’s understand it with an example so here we have action Creator producers views store provider and root reducer component so these can be called as the various roles involved in setting up the components and then ultimately in the data flow now let’s see how the communication will happen among these components so first step is to get the store ready here in the example the store has been hired and the reducer team has been asked to help the store out so here in the example the store has been hired and the Reger team has been asked to help the store out then in the next step that is setting up the communication between the store and other components we can see the example where the root component says to the provider that this store is hired and now the provider has to set up the network to keep the components updated and here’s the view part so view will get connected to the latest updates to display the user now the final step is to prepare the action callbacks so here the view part has to make it easy for dumb components to understand it has to bind the action Creator and the dispatcher so that the dumb component can just call the call back as we know if something has to be updated as a store is immutable an action has to be triggered which can be done by action. Dispatch method now let’s understand the data flow that is how data will flow among all these components of Redux so Redux architecture is concentrated on a strict unidirectional data flow in an application all the data follows the same life cycle pattern making the logic of your app more predictable and easier to understand it also encourages data normalization to ensure consistency the picture represents the flow diagram of the Redux application which contains all the components which we have discussed now let’s understand the data flow with the help of this example step by step starting from here where the name is John we want to update it with something else so it will start from action Creator start starting with the step one so the action type is name update value is John this is available on The View and to change it an action has to be triggered now the Second Step where the store will get informed by the action store has the current state tree and now it will be passed to the reducer to calculate how the new state Tre should look like so in the third step the reducers which are the pure functions will get the previous state or previous State pre and action as input and will provide the new state now in the fourth step the root reducer will provide the sliced state tree to other reducers in the fifth step the other reducers will copy the sliced data and will update it and it will show the root reducer that how the sliced state tree will look like and in sixth step the store will be updated and then store will inform the provider with the new state tree or the new state which will complete the step seven and step eight and finally in the step nine the view the new state tree will be updated which we can reender as the component tree so I would sum up the entire process in the following brief steps starting with initial step a Redux store is created using a root reducer function the store calls the root reducer once and saves the return value as its initial State when the UI is first rendered UI components access the current state of the Redux store and use that data to decide what to render they also subscribe to any future Store updates so they can know if the state has changed talking about the updates something happens in the app such as a user clicking a button the app code dispatches an action to the Redux store like dispatch and the type could be counter or increment the store runs the reducer function again with the previous state and the current action and saves the return value as a new state the store notifies all parts of the UI that are subscribed that the store has been updated each UI component that needs data from the store checks to see if the parts of the state the niche have changed each component that sees its data has changed forces a reender with the new data so it can update what’s shown on the screen now we will see how to use react with Redux so to install this stable version using npm we can use the command npm install Redux and to yarn we can use the command yarn add Redux react bindings are not included in Redux by default so you need to install them explicitly using the command npm install hyphen hyphen save react hyphen reduct you have to add these dependencies along with Babel react and webpack now I will show you a small demo of using react with Redux so let’s start with a demo and this let’s uh first see the structure of the whole project so we have created these folders actions components containers reducers and the main file index.js so these all are the components which we have seen while understanding this reactjs and Redux so starting with this main file so index.js is always the first or the main file of a react Redux application of project so in this we are using a special react Redux component called provider as you can see here so this one is the special component and it makes the store available to all the container components in the application without passing it explicitly so we need to use it once when to render the root component so here you can see we are rendering the root component with the name app so here we are using provider so we have to use it once while rendering the root component now we have created this file by importing all the dependencies required you can see here with the help of import statement we are importing all the dependencies which are required it could be like Redux react Redux or the components or the reducers and all the these things now as you can see here all the dependencies react react Dom and here this react Dom that is actually the data object model which you would have learned in JavaScript so in this file we are calling the utility called as provider to call Root component and now let’s start with the components so here you can see the folder components so these all are the different components which we have created so these components could be presentational components as well as container components so most of the time we use presentational components but sometimes we generate container components as well to connect to the redu store so first of all we’ll see the presentational components so here we have to-do list.js too. JS link doj foo.js and app.js and here this app.js is the root component okay so starting with the to-do list.js so this Todo list.js component or the file contains the to-do list which is showing the visible todos okay and basically these todos are the arrays as you can see here these todos are nothing but the arrays which have been created using three properties you can see here ID completed and text and here on click you can see here on click is an event or a function which is taking ID okay here is taking ID as a number which is a call back to invoke when a to-do is clicked now talking about the other file that is too. JS here it shows a single to-do item here is a property you can see here property types okay so it has a property type which has the event on click and completed and text which shows the completed todos now we have one more component that is link. CHS so it has a link and it will show all the completed todos now then we have the footer. JS here you can see they have different links which are used for the filter as you can see with the help of filter link it allows the user to change the currently visible toos when we will see the output of this application then we will see how we can change the to-do list items with the help of this filter link now talking about our root component that is app.js it is calling all the other JS files which we have created as presentational components you can see here like this add to-do visible to-do list and footer so you can see this footer is also one of the presentational component over here so it is calling this as well and you can see these visible to-do list and add to-do all these are the container components so this root component will call both the components presentational as well as container so as you can see here import as well as the export method okay so initially we have imported presentational component like footer and the container components like add too and visible Todo list now you can see here when you will just over your mouse over here you can see from where these components are coming so you can see from the SRC folder and the container folder we are getting this visible to-do list it is a container component and here for footer you can see it is coming from the components folder this foo.js so this is a presentational component now here we know we require the container components to connect presentational components to Redux so let’s see the container components now here inside the container folder we can see the container components present so these are the visible to-do list.js filter link. JS and add too. JS so starting with the visible to-do list.js which we have created here you can see this file is required by too. JS file which is a presentational component so here we have too. Js which is a presentational component it will require this container component that is visible to-do list.js this is the basic idea and it helps to subscribe to the Redux store wherein we have map state to props here you can see this map state to props which is a special function available in this import connect from react Redux here you can see in this connect function this map state two props is present so it is a special function which will help to subscribe to the Redux store now one thing to pay attention is to import connect function here as you can see while importing we have imported a connect function as well from react and Redux Library what it does is it provides the optimization which avoids unnecessary reentering of the application here we are calling the function with the help of get visible to-do utility so we have a switch case in which we have three cases all these three cases are actually the ACs which are show all then show completed and then we have show activ these are actually the todos the action is to show all to-do items then show all completed to-do items and then show all the active to-do items now talking about this filter link. JS here it is a container component which is rendering the links by dispatching an action as you can see over here with the help of dis map dispatch to props utility which we have got from this connect function which we have imported from react Redux Library it is rendering the links by dispatching the action and now talking about this add too. JS here this is returning the HTML part of the application as you can see here we have input value we have the button submit button so when we will see the output there you can see the HTML part which will be visible on the screen so that part comes from this add too. JS file which is actually one of the container components now talking about the actions now you can see here the actions here action is also one of the major component of our Redux application so here in this actions index.js the actions are add too then set visibility filter and toggle to- do now let’s talk about the reducers after actions we’ll move to the reducers and in the reducers we have different reducers present over here index.js too. Js too. spc. Js and visibility filter now in this index.js we are making use of combined reducers utility and we are combining all the other reducers present as we have seen in the example earlier that we have a reducers team where multiple reducers are the part of that team and they together work so here with the help of this combined reducers utility which we have imported from this Redux library with the help of import statement we are combining in the other reducer functions now as we know these reducers are basically the pure functions so other reducers as you can see over here these reducers are nothing but the pure functions which are returning something based on the action so here you can see they are taking the action with the help of the ID and then they are returning something with the help of the case so they are returning the states as we have understood earlier from the examples and we will make use of of all these reducers here by combining them now let’s talk about the output of this application I hope this structure of our Redux application is clear to you all you can create any of the applications on Redux and now talking about the output so here in the output you can see we have a text box and then the submit button and the other buttons also we will see how they will be used now the basic idea of this application is to create a Todo list okay so here we will add some items which will be treated as the items of to-do list so we can add multiple items in this to-do list and then we can categorize them with the help of clicking on those items that whether they are active or they are completed right now we don’t have any item in this list so let’s insert something so for example we are entering to subscribe the adura channel so when we will click on ADD to-do this item has been added in the to-do list for example we can insert like the video one more and for example we’ll write like writing so all these three items I have entered in this to-do list when we have clicked on all so we can see all the items of to-do list when we will click on the active so we have all the active to-do list items and in completed we have nothing because we have not completed any of these to complete it we’ll just click on any of these so to subscribe I have just clicked on it so this item has been completed now when we will see in active items we have only two and in completed we have the one which we have already completed by clicking on it so this was the output for this application which we have [Music] created so the first factor that we’re going to talk about is the application types or the usage react is used to develop web applications whereas react native is used for mobile application development some examples of web applications created using react are Facebook Netflix New York Times Yahoo mail Etc on the other hand react native is used in mobile applications such as Instagram Facebook ads manager Bloomberg Airbnb Uber Eats Etc setup and bundling react native is a framework of JavaScript and it comes with all the essentials that you will need to set up and for the development of your application react on the hand is just a library of JavaScript therefore when you use react you will need various other tools for setup and development live reload live reload or hot reload as mentioned earlier is a feature that allows you to code as well as see the modifications in your application simultaneously react native supports live reload whereas react does not template rendering both react and react native use jsx for the development of views or the templates but react is much better better when it comes to styling your application’s UI using CSS react native on the other hand makes use of native platform apis learning curve even though react is not very difficult to learn react native is much easier this is because you can make use of readymade components and react native while for react you will have to quote them yourself so we’ve done a head-to-head comparison between react and react native the answer to which one is better among the two depends on the type project that you’re creating if you are focusing on creating the UI for a web application then react is what you need but if your project is going to be a mobile application then you can go with react [Music] native angular was developed by Google and its first release dates back to 2010 the first version of angular was also known as angularjs on the other hand react was developed by Facebook in the year 20 13 so coming towards the architecture of these Frameworks angular and react both are component based Frameworks but angular makes use of typescript and HTML whereas react which is a user interface Library makes use of JavaScript and jsx jsx is nothing but a syntax extension for JavaScript the latest version of angular that is angular 9 was released on the 7th of February 2020 one of the core features of this major release is the angular IV to know more about the angular IV you can check out the angular 9 video and blog from Eda whose link is mentioned in the description box below talking about react the latest major version of react is react version 16 the rendering process angular performs client side rendering however it can be rendered on the server side as well using nodejs on the other hand rendering is done on the server side in case of react websites built using these Frameworks YouTube as we all know is the world’s largest video sharing platform owned by Google and this is built on angular another very popular online payments application website PayPal also runs on angular other popular websites that use angular are Walmart which is a multinational retail Corporation and gmail which as we all know is an email service platform I’m sure after listening to this many of you would have felt wow angular is amazing but let me tell you guys that react is nowhere behind Facebook is the developer of react and yes Facebook makes use of react as well other popular applications such as Instagram which is a photos sharing platform and WhatsApp which is a crossplatform messaging app Airbnb where you can book your stairs for your vacation are also built on react so moving on towards the licensing of these two Frameworks both angular 9 and react 16 come under the MIT license MIT or the Massachusetts Institute of of Technology license is an open-source license sometimes it’s also called as the BSD style license and it has minimal software redistribution requirements the DM or the document object model angular makes use of real DM while react uses virtual dor the real dor updates the entire tree structure for HTML tags it does not make much difference in a simple application but if you’re dealing with a large amount of data requests on the same page it affects the performance as well as the user experience hence real dorm actually offers low performance with complex and dynamic applications at times real domor becomes extremely difficult to handle because the whole tree data structure is updated even if a minor change has been made virtual dor on the other hand has its components attached this gives the comfort of navigation within a website virtual Dom is also a node tree that lists out elements and their attributes as objects reacts vender function creates a node tree out of the react components then it Updates this tree in response to the mutations in the data model caused by various actions done either by the user or by the system virtual dor is not browser specific and it is lightweight it is provided in react package for free and eliminates the issues of slow performance of real dor having said this I’m sure you would have understood that virtual dor is better than real dor data binding angular uses two-way data binding event binding and property binding in event data binding angular allows you to bind events along with the methods property binding of angular will allow you to pass data from the component class and set the value to given element at the user end property binding also allows you to control elements property two-way data binding is a very important feature of angular with this angular allows you to make changes from the views to the models and from the models to the Views react unlike angular allows one-way data binding here the UI elements can be changed only after changing the model State the developers however cannot alter the UI elements without updating the corresponding models a great advantage of using the one-way data binding is that throughout the application the data flows in a single Direction which gives you better control over it this makes our application more flexible and leads to increased efficiency so talking about the latest features of angular 9 and react 16 angular 9 has a number of new features which are compilation of application with IV is default in angular 9 your angular 9 application is compiled ahead of time this means the angular’s aot compiler will compile all the HTML and typescript present in your code into JavaScript before your browser downloads and runs it this conversion takes place during the buildt process itself and it also also includes type checking angular 9 requires typescript 3.7 any lower versions are not supported TS lip or the typescript runtime library has also been made a pure dependency rather than a direct one earlier this library was installed automatically but now you will have to explicitly add this using npn or Yan react version 16 allows you to build great user experience models with concurrent mode and suspense concurrent mode is a feature that helps in binding apps faster with great user experiences that can help developers achieve their goals suspense is also a powerful tool for carefully organizing An Elegant loading sequence with a few well-defined states that progressively reveal the content the next very important feature is that react allows you to easily create Dynamic web applications and mobile applications react also provides support for custom Dom attributes instead of ignoring unrecognized HTML and SVG attributes react will now pass them through to the Dome this has the added benefit of allowing us to get rid of most of react’s attribute white list and it helps in reduction of the size of the application react as I’ve already mentioned earlier has a single way data flow that offers a better and streamlined data overview in react version 16 there is an increase in productivity that helps in maintenance of the react project reusing components is the major advantage of react you can start with the usual components like checkbox button Etc once this is done you can move to rer components which is comprised of internal logic which makes it easier to manipulate and Define objects that are used this also ensures the consistency of application and facilitates the code maintenance react version 16 also provides better server side rendering and error handling in this version the server is completely Rewritten and it is very fast it also supports streamlining so you can start sending bytes to the client faster so now moving on towards the next comparison factor which is the speed and productivity talking in terms of angular earlier angular was heavier and a little slower compared to react but now thanks to the angular CLI that the app size of angular has been drastically reduced and offers enhance development experience the angular CLI empar in creating a workspace and Design functioning applications quickly it also empaths in producing components and services with on line commands angular CLI ensures the clean coding feature of typescript before I start the discussion over react let me just tell you what is reduxx rux is an open-source JavaScript library for managing the state of the application it is most commonly used with react for building user interfaces so coming towards react the development speed and productivity slightly get affected due to the involvement of thirdparty libraries like reduxx however react is easier lighter and faster to code when it comes to small projects but for large projects typescript is preferable as it contains numerous features and components therefore angular has an edge over react when it comes to speed and productivity deployment earlier it was complicated to deploy an angular app but now thanks to angular Firebase angular 9 has officially added support to Firebase and angular apps and therefore angular apps are now easier to deploy to Firebase react as I’ve already mentioned earlier is lighter and the size of the application is smaller therefore it becomes easy to deploy the applications created using react these applications are usually deployed using node.js the learning curve learning curve in angular is quite steep as angular provides numerous features options and components for react the learning curve is easy as react is relatively small library and has fewer Concepts to learn when compared to angular and for those who want to learn web development quickly and the project requirement is not too large can go along with react so now coming towards something very important and interesting which is the market Trend the numbers that you see on the screen are taken from Tech Trends website according to Tech Trends there is a close competition in the job market for both these Frameworks however angular holds a slight upper hand overall moving on towards the final factor of comparison which is community support according to the 2019 stack Overflow survey it is clearly shown that react has stopped among the web Frameworks making react the most loved and supported framework by developers however angular is not far behind as it has good developer support by Google both these Frameworks have very good Community Support [Music] now let’s start with the realtime projects which we are going to discuss in this session so as you can see on the screen as well we are going to discuss this pick it up an e-commerce app chatted chit that a chat app fabook a social media app show it off a video sharing app short it out a URL shortener and groov on a music streaming app so let’s just start with this starting with pick it up an e-commerce application I think most of us are very much familiar to e-commerce apps as we know an e-commerce app allows users to add or remove items from a shopping cart view the card and check out using different payment methods so for inspiration you can check out some simpler storefronts like a Shopify storefront as well as massive retailers like Amazon or Walmart now you might have question that how to build this so to build this you can start with creating the app with create react app and add the stripe npm package plus use shopping cart to easily handle payments directly with strip checkout build a node API to handle creating sessions with a strive and then you can deploy it the back end to Heroku front end to ntif fly or you can deploy both on Heroku as well now moving on to the chat app that is chitted and chat that so whether it’s a mobile application like WhatsApp or Viber or a productivity tool like slack or Discord all of these use some kind of realtime chat app it could also be part of a chat widget within a website where customers can directly talk with the site owners now as we know all chat apps allow users to send messages to others in real time react to messages show when they are online or offline for example you can check out slack messenger Discord crisp chat Etc now answering the question of how to build this app so we can start with creating the project with create react app then use a service like Firebase or graphql subscriptions to create and get realtime messages then we can add reactions to message with Emoji using the npm package Emoji M then we can deploy to the web using Firebase tools now moving on to favebook a social media app the app you’re likely most familiar with is a social media application in many ways it’s similar to a chat app but expanded to a larger community of users these users can interact with each other in different ways so a social media app allows users in such a way that they can follow one another to receive their posts add media like images and videos to share with others and interact with post such as liking or commenting on them for inspiration you can check out some real-time examples like Facebook Twitter Instagram Etc now answering the question of how to build this so we can start creating the front end with create react app and creating the back end using a node API then we can use a database like postre SQL or mongodb along with an OM like Prisma of postre SQL or of mongod TV then we can use social authentication with Google Facebook or Twitter using OD zero react or passport.js then finally we can deploy it deploy the backend to Hoku and front end to nlii now let’s move on to show it off a video sharing app a video sharing app is probably the most Broad category as video is used across so many different apps and in many different ways you have video sharing apps like YouTube which allows you to search any browser and look for any video that you could imagine that users have created also Snapchat give us the ability to watch videos from other users that are recorded in a much shorter and more accessible format and they are more oriented around interactions such as likes and Views now let’s see how to build it so we can create the app with create react app and then we can create the back end with node or Express then we can use cloudinary for image and video uploads to the cloudinary API then we can use a database like postre or mongod DB along with an or like Prisma of postra or of mongod then finally we can deploy the back end to Hoku and front end to netlify or we can deploy both on Hoku as well now let’s move on to short it out a URL shortener a URL shortener is basically a simple tool that takes a long URL or the link and turns it into a short URL as we know or you might also not know that URL shortener with support for custom domains allows users to shorten the URLs manage the links and view the click rate statistics for inspiration you can check out some real word examples like cut bitly Etc now let’s see the steps to build this application so create the app with create react app then create the back end with node or Express and you can use a database like postre SQL or mongodb and then we can deploy this to the web using Firebase tools now let’s see groov on a music streaming app just as react applications are perfect for serving video content they are also great for streaming media like music music apps have a similar structure to video sharing apps and may or may not allow users to upload their own music but they do allow users to listen to music like songs comment on songs or even purchase the music even music streaming app can combine elements of a video sharing app as well as an e-commerce application for inspiration you can check out the regular music apps to which many of us switch to almost daily like Spotify SoundCloud Pandora Etc now let me give you an idea how to build it so create the app with create react app then create the back end with node or Express and use cloud for image and video uploads to the cloud API then we can use a databases like post SQL or mongodb and then we can deploy it to the web using Firebase tools now we have discussed about some interesting and full-fledged projects of reactjs now let’s see some small projects which could be a very good good source of enhancing the Practical knowledge of reactjs for beginners there are many example projects created by the react Community now we will see some of the projects that use react without third-party State Management libraries so starting with the calculator it is implementation of the iOS calculator built in react in this you just have to create an UI which can perform mathematical calculations talking about Emoji search react app for searching Emoji so everyone in daily life uses some or the other chatting app where we can do without appropriate emojis or the emoticons so you can just create that emoji search feature using reactjs talking about snapshot a photo gallery with search we can search particular picture with Associated keywords or tags and that’s we need to do in a snapshot using react talking about the image compressor and offline image compressor built with react and browser image compression many of times we need to compress out images to upload somewhere or for storage and every time going for online tools not a good idea right so just create an offline tool with the help of react CHS so these were some small projects which can be created using react JS now let me just summarize it so react GS developers have a bright future ahead as the technology is in Ed in several Industries in fact as opposed to other web development Technologies the react developers are now paying the most with react one can function both on the client side and the server side it facilitates the development of larger applications with its portion and data patterns that improve readability thanks to its versatility increased performance and improved usability features it is an outstanding front-end development program which can be used to create as many many Innovative projects as possible this testing is a very important part of your application because when the application goes live we always have to test our application to make sure it’s working fine because if something got break at the end of the deployment on real time it is very difficult so we have to make sure everything run very good so here software testing is a process to evaluate the functionality of software application with an intent to find whether the developed software met the specific requirement or not and produce of bug free products it’s very important part why should you perform testing cost of fixing the bug is larger if testing is not done at early stage once the application deployed it become very difficult to handle so we have to make sure that we should get it on the early stage only we try to fix that to produce good quality product to make software application defect free to check if the behavior of application is same so the testing also do one more thing that testing help us to verify that the thing we expect is same as it’s there or not to check if the behavior of application is same in development and production environment the type of testing unit testing functional testing and integration testing unit testing unit testing is used to test a small piece of independent code unconcerned with how they are wrapped in your application to prevent regression easy to pinpoint and fix the problem if take longer to execute it likely the code under test is much more complex it should be popular tool to perform react testing is just an enzyme so basically unit testing is more like the way the piece of a code that you right you want to test that code is basically come under your unit testing functional tests are made against combination of many units they use any number of external object or system like database UI security as it testing that how as a product is behaving take longer time to execute the unit test functional test represent major release whereas unit test represent only minor change due to which they’re expected to change less often than a unit test when user entered username and a password and click on send that user will be logged in we can easily see that this function group will compromise for many unit test one for validating username and one for handling a button and so on and an integ testing we ensure system application working correctly it can execute only with the realistic involvment like real database server and other system which like to Target production envirment it is used in case you need to test separate system like database and application it is lower than test say other test and is complex to write a functional test May successful test and ability to idle system to open help dialog box but with integration testing with a new browser or other runtime it found that expected functionality is not achieved test application using zest and enzyme so what is zest zest is a fast testing framework it act as a test Runner assert library and moing library and whereas enzyme is a JavaScript test utility for react that make it easier to assert manipulate and derse your react component output so enzyme provide additional utility methods for rendering a component finding element and interacting with element so basically the component testing or the snapshot testing the one we are talking about is actually achieve using enzyme also on the other side if I talk about create react application setup come with bundle with zist generally what happen when we start writing a test cases we look for a testing but basically your react script package that you have created or the sca folding that you have created is actually come with the zest package inbuilt so you don’t have to install a zest but apart from that we have to install certain other things so now we have to a test with the say snapshot integration with reducer so let’s perform that this is our application that we are working in the Redux on this application I’m going to do some testing first of all I’ll open that in vs code let’s go there now particularly in the vs code so I’ll open our folder and we have to install certain packages for this although as we know zest is by default in built but apart from zest we’ll install certain packages so first of all let me open our folder our application is already running so I’ll stop that and let me install some package there with my command prom I’ll open that I’ll stop it manually and first of all you have to install npmi react test renderer and we need enzyme adapter react so I’ll write enzyme adapter react 16 apart from that as zest is by default there we just need one more enzyme so we need three package one is enzyme one is enzyme adapter react 16 and one is react test render so we install that now while it’s installing we’ll proceed with our next part now it install so we can go back to our application here whenever we have WR any test case so in the SRC folder we have one test folder I’ll do one thing I’ll delete this test folder and write a fresh test folder for us and the test folder should be name as underscore uncore testore uncore now here first of all let’s do a oneof a component testing so if we go back to our component we have one footer component let’s test this component we’ll verify that is that component is as expected or not what we’ll do we’ll make a one Json tree for that and then with that Json tree we’re going to use it it should be a part of our test folder component. test.js so remember one thing your file name should always add with means have test between that and see the color difference also there because it detected that’s a test code now you have to import react here import react from react then you have to import footer first of all from dot slash at least should be do do slash it’s a twofold route component slash footer then we’ll import create that is coming from react test renderer now what we’ll do is we’ll let have one describe keyword so we’ll describe what this test Cas is all about I’ll say it’s a snapshot test for footer now after that we’ll call that function Arrow curly braces we WR test it should be test and we’ll write testing footer anything you can say here it’s a name by which we test what this test case all about after that bracket Arrow curly braces we’ll say let tree equal to create so create footer we’ll make our one Json of footer then after that what is expectation my expectation is 3.2 Json to match snapshot if it match snapshot test case pass else test case fail to match snapshot like this now how to run it just go back to a command prompt and simple run a command npm run test if the test case pass it will show you pass else it fail if the test case pass it is see automatically pick that now spelling mistake is there see it automatically able to pick my test file now it’s running test case pass and your snapshot created in case if I go back and make change in a footer say urea n anything now the test case will fail because it’s not matching the required criteria if I go back and make it back it will work suppose your requirement is that suppose requirement got changed now I want to update my test case because it’s once created it keep on failing so what you can do is as you have this test you can add the update test like this test update upate react script test and update snapshot the second way that you can do now here I’ll add one more test case I’ll say one we did for our component test now we’ll do reducer so I’ll pick that test case and I’ll walk you through how exactly it work now I have a more test for reducer in this I import reducer first of all see what reducer is returning we have to run a test case according to that right now my reducer is returning article and gallery and I test case expectation is same it’s say initial State should be article and gallery later on when we actually pass that particular I’ll say action it should return array so how exactly we can do that so this is where are two test case One initial State one when we pass the action if I go back and I run this see this time three test case and all three pass as it returning me object initially after calling action we got array so now we’re going to talk about maintaining code using G see what happen when n number of developer are working in the application everybody have to sync their code because it’s not possible like one day we give one folder to someone and then they will update that folder they give us back it’s not possible the reason for that is till what extent you keep on doing like this you always have to work in the way that you always upload the code somewhere and those who need the code they will download the code and the code should be keep on in syn now to achieve this functionality we use the GitHub so with the GitHub it become in the way that we can share our code very easily so Version Control is one that record changes for document computer program large website and other collection of information over time it allow multiple user to manage multiple revision of same unit of information it is used to maintain the record of different versions of code the most popular tool used as Version Control control is git why should we use git git is a open source distribution control system for tracking change in source code during software developer snapshot get change made to file rather than itself that mean if file is not changed it is not stored again distribution every user have his own copy which store data locally basically what happen we have a data locally and from there we push fast operation almost every operation on a gate is local hence the speed off by get is lightning fast compared to other tools Branch handling every collaborator work directly in the separate Branch basically if I have something to push I’ll push in my own separate Branch rust nearly every task in get is recorded and hence hard to lose any data the git workflow is like that use git flow to manage your project efficiently work with set of guidelines increase G consistency and popularity if I talk about one by one that Repository is a server where all the collaborator upload change made to the file then local repositor is a copy of database the user all the data file locally through push then working copy is a space where user active directory the user modify existing file and create new file in the space then staging area is a place where all the modified file are marked to be committed our place commit command commit all the file in the staging area to local Repository and push command move all the data in the local repository to remote repository when we do fetch fetch collect the change in remote repository and copy them to Local repository whereas a pull pull the latest change in the code so let me show you how exactly we can push pull the code in the GitHub now for doing that what we’ll do is so let’s go here so this is my GitHub if I want to make any new repository where I can push the code what I’ll do is I’ll go here click on the icon and say Eda like that after that I’ll create one repo now one repository by name of edria created it give me this five commands so now what I’ll do is on my local system I’ll make one folder from where I want to push any code suppose it’s my local system it don’t have anything suppose I’ll take few files here three files I pick I’ll move these three files here now I want to push for a Windows system you need to have a g bash which is already there in this machine right click G bash here we write one by one command the very first command is git in it basically we initialize the git in this folder sorry let me minimize it first of all we minimize the code in this folder like say I’ll say git in it this will initialize the git in this folder I say your hidden folder will be created once you do like that your hidden folder will be created in the gate so let me actually close this one and if I go to view know and I say hidden files item see one get folder created right then you have to add all the code a get add then you write get commit it will commit all the code in a local repository write some command so it say that you’re pushing it first time so you have to set your Global username and password so how we’ll do is we’ll say get config the very first time you’re doing from system you do like this get config hyphen hyphen Global we’ll say user . email so I’ll add my email ID here you have to give the email ID by which you have signed up on the G I’ll add that email ID here it’s wrong email id id you will not take it then then I write here my username of this that is aash developer get config minus minus Global and then I have to say user.name and that is Akash developer like this and now it’s set now you try to commit the code it say still something is missing although we have already done that so it’s actually helped to set a global username first of all let make sure we’ll say get config Hy Global user. email now it is done and then user.name now see it’s committed after that in whichever Rao you want to push you have to pick that path of the trpo like this so I’ll go back and particularly paste it and enter at that and we’ll say get push minus U origin Master like that now this will push the code to this repo tomorrow if anything new want to push just three command get add get commit and get push ask my username and a password I’ll enter that so guys means first time you push like this next time when you want to push you just write get add get commit and get push that’s it now it’s done so see it’s pushing that code if you go back to get your code is pushed next time also get add get commit get push now suppose I open any file and some edit there I write here aast developer or I write something different say developer funnel like that anything I can write here now once I write and I commit the code so suppose some other developer already pushed some code there now what you have to do in your G you will write get pull so the latest commit what whoever made is pulled see creating a remote repository we have already seen how exactly we add the code to the G so we already in the last demo we have created that repo we have given a name and we created that now to push the code we need to have our get bash after that we did get in it then we config that after that we added the remote where you want to push and then we committed that code once it commit it goes to the master Branch after that that suppose if I have to take some different branches like so remove the code we’ll say get RM and the file name get cache or the error showed up if you try to delete the stage file you can force delete by adding minus F to that I’ll show one more thing here suppose I want the two developer are working we can make a branch also we’ll say get checkout minus B checkout now what this will do it make an separate Branch for that I’ll say new feature any name I can give like this now if I add add some file in the folder suppose I’ll create one new file in the folder random file now when I push this s I’ll say get add get commit then get push in that Branch get push minus U origin and the branch name that is new feature that Branch name enter wrong and plus get command was wrong so I have to correct that both the things now this time it’s going to push in separate branch and see on the git we get something in terms of like pull request so what we do in real time we say compare pull request if everything’s look good we can add the reviewer and create that once you read the pull request your reviewer will review the code if they find everything fine they merch so what happened once they confirm merch your both the branches got merch but you’ll see two Branch [Music] here so starting with answering who is a react JS developer reactjs developers design and Implement user interface components for JavaScript based web and mobile applications using the react open-source Library ecosystem these skilled front-end developers are involved in all stages of interface component design from conception to final testing from conception to testing a topnotch react developer can help build interactive components for websites or web applications using the react development Concepts today more and more Enterprises benefit from reactjs a testament to its bouring popularity in software development some of the high traffic websites that use react are Instagram Uber Facebook Twitter Reddit Etc along with the upswing in react usage is the surge in demand for a reactjs developer a highly skilled react developer is involved in the entire stages in the development and maintenance of user interface components a react developer is responsible for Designing and implementing UI components for JavaScript based web applications and mobile applications with the use of open-source Library infrastructure these developers are a part of the entire process starting from conception to the major testing process and follow popular reacts workflows like flux and Redux reactjs developers are front-end developers who build modern-day UI components to improvise applications performance they leverage their knowledge about JavaScript HTML CSS and work closely with testers designers web designers and project managers to create a robust and effective application so I can sum up as reactjs developers are also known as front-end developers who design and Implement user interface components for JavaScript based web and mobile applications using the react open-source Library ecosystem now moving ahead I’m going to discuss the job opportunities for a react GS developer there are thousands of jobs in the world which demand reactjs skills talking about the numbers there are more than 43,000 jobs available on LinkedIn alone in India for react as compared to 2019 there has been 184% of increase in the openings for react GS developers in the year 2020 according to India Today a quest report States after covid-19 that is in 2021 reactjs developer is one of the top digital skilled jobs in demand this quite a huge number of job opportunities makes react one of the skills most of the application developers want to learn and secure a good job moving ahead let me discuss the salary trends of a reactjs developer of course of course salary is important today react has the best pay scale on most of the job suggesting websites like LinkedIn glass store pay scale Etc reactjs developers salary depends on multiple factors like years of experience different roles held over time level of expertise special skills training and certifications and also the geographic locations the average salary for a reactjs developer in India is 79,81 92340 now as I’ve told the average salary for a reactj developer in India is [Music] 79,80 K for frontend developer or engineer the average salary of 650 4K for software engineer and the average salary of 1 million for senior software engineer now moving ahead let me show you the job description which have been posted on different job suggesting portals by top organizations so first for example we have Tech Mahindra the designation is react developer and the locations are Bengaluru Hyderabad and Chennai in their job description they have mentioned the skills required for the candidate it includes btech is a must mte or MCA with relevant experience so they are talking about the graduation and the degree which is required talking about the react skills so as you can see they need a react developer with front-end technology with Redux or d3.js experience they need a candidate which has strong Proficiency in JavaScript including Dom manipulation and the JavaScript object model the candidate should have thorough understanding of react GS and its core principles and experience with popular react GS workflows like flux or ruxx the candidate should be familiar with newer specifications of ecma script which are known as like es6 es7 es10 Etc and restful apis the candidate should be familiar with modern frontend built pipelines and tools and should have the experience with common frontend development tools such as Babel webpack npm Etc the candidate should have the ability to understand business requirements and translate them into technical requirements and familiarity with code versioning tools such as git SVN Mercurial and similar and the candidate should have a knack for benchmarking and optimization if your skill set is matching to this job description you are good to go now let’s see one more job description from EX censure where their designation is reactjs application developer and the location is Bengaluru they require be or preferably certified as technical architect associate they need a full stat developer who has worked with react spring boot or Java microservices the candidate should have an experience of one year on most of react GS bootstrap engin Docker weback J or JavaScript and for backend the candidate should have minimum one year of experience on nodejs python AWS Lambda darker just unit test or P test and the candidate should be a developer with one to two years of experience and a passion for Quality good design and
clean code so if you are matching this criteria you are good to go for this job so as you have seen some of the job descriptions from different companies now I think you have an idea how to prepare for the jobs for reactjs developer now moving ahead I’m going to discuss the skills required to become a reactjs developer as we have seen in the job descriptions as well so I’m going to explain those skills now starting with basic programming and development skills which include HTML CSS JavaScript reactjs G HTTP protocol and terminal talking about HTML and CS no front-end developer is a stranger to HTML and CSS the ability to work with and craft user interfaces is necessary to every organization at a high level react developers should be able to work with and write centic HTML tags work with and write CSS selectors Implement a CSS reset understand the Box model and how to reset to border box understand Flex box and work with an implement responsive web principles including the proper use of media queries talking about the JavaScript fundamentals including es6 you can’t rock react without a firm understanding of the fundamental concepts that the JavaScript language provides but these es6 skills are also essential which include variables and scoping arrays and objects array methods functions and arrow functions in react every single component you build is a function in one way or another remember that classes are just Constructor functions under the hood regardless of the syntax you are using when building functional components or class components you are using some form of a function and then comes the react this is the main deal you got to learn react and learn it well to become a react developer while learning react you should focus on the topics like routing GSX Etc talking about GSX in react you never really touch HTML proper you work with a syntax extension that is truly one of the most remarkable part of the react ecosystem that is jsx jsx looks so much like HTML you may think of it as HTML flavored JavaScript what’s cool about jsx is that if you know HTML and CSS you intuitively know how to work with jsx jsx is an abstraction on top of the react. create element API one re reason it is vital to the library and why the react team chose to go with it in the first place is that the API would be too cumbersome to use in terms of scaling one potentially could use react. create element to build out an entire application however this wouldn’t be any more efficient than just using HTML proper it may feel at first that we have taken a step backward by adding our markup into our template logic however a few quick minutes with GSX and you will be hooked on the style and now we have new jsx transform as well so you can explore that as well in react you should learn Dom manipulation and event handlers the disc keyword higher order functions and call back functions prototypal inheritance and object creation and the class keyword it doesn’t matter whether you are a front-end developer or a backend developer or even a full stack software engineer you must absolutely know get in 2021 try creating a few repositories on GitHub share your code with other people and learn how to download code from GitHub on your favorite ID git is essential to every developer toolkit for storing projects on Solutions like GitHub bitbucket and gitlab and the skills that should just be part of your day-to-day include tracking changes with ADD commit push and pull branching and merging strategies and handling merge conflicts you should know https protocols like if you want to become a web developer then it’s an absolute must to know HTTP and know it well I’m not asking you to read the specification but you should at least be familiar with common HTTP request methods like get post put patch delete options and how HTTP and https Works in general and you should learn the terminal as well though it’s not mandatory for a frontend developer to learn Linux or terminal I strongly suggest you to get familiar with the terminal configure your shell which includes bash zsh CSH Etc while I’m talking about the skills so you should also be familiar with the build and State Management tools which include node node may be a surprise to many like why would you need to know how to work with node in order to be a client side react developer so the answer is high server load using node with react makes sense when you web application needs handling of multiple requests and maintaining server load balance and react developers need to have a solid understanding of the npm registry this is the place where software developers can go to get software to help them build software sounds funny but truly that’s all the npm is a cloud storage for packages we call dependencies and as you can see on the screen I have mentioned npm or yarn so Yar is a package manager that is built to utilize the npm registry Yan actually optimizes your npm workflows Yar and npm somewhat compete today but the mission of Yar has been to solve a lot of problems that are accepted in the node npm ecosystem npm has been doing everything it can to follow the patterns and practices that yarn presents then comes create react app so it is like a quick start to create a react application you can just install create react app and you can just start with the default application you can add the components in that you can make the changes and you can get your react application ready then comes the web pack and Redux so react has built in State Management and many developers have been bored along the way by discovering the asynchronicity of State updates and how react handles them for that reason and for scalability Redux Wass born Redux is a state management library and more it’s not a framework but an opiniated way of working with data the principles behind Redux are along the lines of functional programming and immutability but it’s not a one- siiz fits all solution mastering the concepts of fundamental react programming prior to diving into Redux is key then comes Redux tongue which is a middleware and comes the flux so flux is also a workflow like Redux so you can choose whether to use Redux or flux depending on the requirement now talking about other utilities like API clients server side rendering tools and testing libraries so in today’s world you will rarely build an isolated GUI that is graphical user interface instead there is more chance that you will build something which communicates with other application using apis like rest and graphql thankfully there are many API clients available for react developers which include rest rest API actually in that we have fetch super agent Etc then we have graphql which includes Apollo relay urql Etc then talking about the server side rendering tools you might be thinking what is the difference between server side rendering and client side rendering let’s clear that before talking about the library which supports server side rendering with react well in client side rendering your browser downloads a minimal HTML page it then renders the JavaScript and fills the content into it while in the case of serers side rendering react components are rendered on server and output HTML content is delivered to the client or browser for server side rendering you can learn next.js or after. JS or roll but I suggest learning just next.js should be enough and testing is one of the important skill for react developers which is often overlooked but if you want to stay ahead from your competition then you should focus on learning libraries which will help you in testing for unit testing you can go for just enzyme sonon moocha Ava tape Etc and for end to end testing you can go for selenium web driver cucumber. JS Etc and for integration testing you can go for karma you can learn the library you want but gist and enzyme are recommended and I want to add up one more thing for virtual reality if you are interested in building virtual reality based application then also you have some framework like react 360 which allows you to exciting 360 and VR experiences using react so if you are interested in that area you can further explore react 360 now comes the soft skills so to become a reactjs developer or any software developer be it front end or backend some of the soft skills are always required by the companies which include competence to translate business needs into technical requirements time management project management communication and interpersonal skills capability to write crisp and clear code problem solving and troubleshooting skills creativity and accountability open-minded team player willing to accept feedback and offer suggestions Etc and you should be having willingness to learn modern-day tools and processes as everything updates very quickly in today’s world and then as you can see on the screen I have mentioned UI and ux so as a frontend developer you must be familiar with the UI and the ux part of the application now I’m moving ahead with the road map to become a react GS developer so to become a reactjs developer you should follow a road map in which you should be familiar with the programming and in programming the skills which I’ve already mentioned you should learn those and then comes a reactjs which is the basic or the main thing which you should be familiar with then you should be completing some of the projects and you should be familiar with tools and utilities which are supporting reactjs and you must have graduation degree and accordingly you can go for the certifications as well which are mentioned in the job description in the particular company for which you are going to apply and also if you are not a fresher you should have the relevant experience as well and to to become a reactjs developer you should set some of the timeline or some deadline within which you will complete all the learning you will attain the required skill set to become a react GS developer the skills which I have mentioned you can go for that so you can attain strong Proficiency in JavaScript object model Dom manipulation and event handlers data structures algorithms jsx and Babel then you can go for understanding reactjs and it’s Main fundamentals like jsx virtual Tom component life cycle Etc you should be proceeding experience with reactjs workflows like flux Redux create react app data structure libraries Etc you should understand the restful apis or graphql HTML CSS es6 code versioning tools like git SVN Etc then popular frontend development tools cicd tools devops performance testing Frameworks like moocha just then you can go for node plus npm and you should have preferred degree in computer science information technology or similar and to help you out to attain all these skills in a proper manner I have some suggestions like you can go for eda’s reactjs certification training course so in this training course you will be trained to build efficient react applications by mastering the concept CS of react Redux and react native as well in this react course you will learn how to build simple components and integrate them into more complex design components and after completing this react online training you will be able to build the applications using react Concepts such as jsx Redux asynchronous programming using Redux Saga middleware fetch data using graph ql perform testing using chest successively deploy applications using ngx and Docker plus build mobile applications using react native and also you can go for react documentation whenever you have any doubt or whenever you are stucking somewhere and you can go for GitHub there so many projects are available which you can clone or take help to build your own and if you have any doubts for which you need some answers you can go for GitHub as well now moving ahead let me discuss the roles and responsibilities of a reactjs developer a skilled react developer makes it painless to create high quality web applications with elegant uis using the react Library reactjs developers bridge the gap between the visual aspect and the server s side component they take a proactive role in streamlining the look and functionality of the applications as an efficient reactjs developer he or she is supposed to perform certain defined roles and follow respons responsibilities to get the best of results here are the major ones that any reactjs developer is supposed to follow Leverage The inbuilt react toolkit create data visualization tools libraries and reusable code for prospects integrate designs and wireframes within the application code monitor interaction of users and convert them into insightful information write application interface code with JavaScript enhance application performance with constant monitoring translate wireframes and design into good quality code optimize components to work seamlessly across different browsers and devices good understanding of CSS libraries git Sigma Adobe XT Etc proper user information authentication and develop responsive web- based UI and if I talk about non-technical roles and responsibilities so it includes constant interaction with other developer teams and design team to discuss UI ideas a thorough review of applications needs and interfacing elements and follow proper documentation for changes in application and further updates now let me discuss why is reactjs in demand reactjs being a multi-layered library has been a key Delight for developers and organizations alike reactjs developers Have Been instrumental in assisting business owners to to focus on their Core Business areas without having to bother about other it related activities this has helped big time in enhancing client satisfaction some of the features of reactjs which have increased the demand of reactjs are flexibility reusability strong documentation and Community Support fast rendering single page loading and easy debugging so when I talk about flexibility it is especially visible when it comes to the use of react for web development when we talk about react’s flexibility we refer to the libraries innate modularity as we know react’s architecture allows bundling frontend code into custom components this providing a solid foundation for the overall development process optimization reactjs allows you to write clean modular code breaking the project into separate components as a result when code is modular it gets easy to maintain and scale react is super flexible in the sense that it can be integrated with other third-party libraries and MVC Frameworks you can choose to create a react project from scratch or gradually introduce react to your existing code base and when I say reusability react doesn’t require big lines of codes to program an application in react we say that everything is a component a user writes small codes called components and combines them to form another component simply any app made with react is a tree of component so react follows right once and use it anywhere principle then comes strong documentation and Community Support being an open source Library react has what it takes to keep attracting more and more New Comers to its Community which makes it only stronger over time as of today react is one of the five top rated repositories on giab with over 170k stars and over 5 million applications publicly admitting to using it react has a rich ecosystem to benefit from or contribute to besides finding one’s way around all this information won’t be a big challenge as the react documentation can be easily found on the official website the community is active so you can get rapid feedback or response to your inquiry once you feel stuck currently on stack Overflow there are over 14 million questions tagged react GS that have at least one accepted answer so once you encounter a problem chances are someone has already had same problem and there is a solution to it so that you will only have to copy paste it from the corresponding discussion thread talking about the fast rendering so react is a client side JavaScript library that uses server side rendering react’s virtual Dom is basically the prime cause of faster rendering and the better performance of react apps and this react virtual D serves as a layer between how things are supposed to look and the actual processes happening to render all of those things onto the page and the single page loading so due to the single page loading with the help of virtual term this fast rendering is achieved and then we can talk about the easy debugging in react props and estate are the bread crumbs like when something goes wrong it is important that we have breadcrumbs to trace the mistake take to its source in the code base and if you see something wrong on the screen you can open react div tools and find the component responsible for rendering and then see if the props and states are correct if they are you know that the problem is in the component’s render function or some function that is called by render function the problem is isolated if the state is wrong you know that the problem is caused by one of the set State calls in this file this two is relatively simple to locate and fix because usually there are only a few set ofate calls in a single file and react results in not only easy debuggable code but also highly testable applications with the help of chest or enzyme Etc now let me discuss the future of react GS developers reactjs developers surely have a promising future since reactjs is showing no chances of turning back as you must have seen the requirement for reactjs developers on different jobs suggesting portals and on LinkedIn itself we have 43,000 and more jobs for reactjs developers we have 170k stars on GitHub so many requests for the applications and more than 90,000 live websites are using reactjs and a lot of organizations have started migrating to react so they definitely need more and more RS developers now as compared to other peer comp competitors react CH developers are being paid heavily and are in demand Facebook and the entire Community have been trying hard to keep enhancing the effectiveness and speed of reactjs hence it is imperative that reactjs will keep fighting the competition hard and come out as a winner newer updates and ways of rendering are expected soon the way it is growing the demand for reactjs developers is exponentially higher to sum up I would say the word is unquestionably changing in Rapid and dramatic ways and the demand for reactjs developers is going to keep increasing for sure now after discussing a lot of things and addressing a lot of questions I hope you have got the idea how to become a reactjs developer from where to start how to start what skills are required why those skills are required Etc all these questions have been addressed [Music] I will discuss the questions on four topics of react which are being frequently Asked in react interviews the topics covered today are react GS Basics or the general react then reactjs components then we have reactjs Redux and reactjs router now starting with the general react questions so the first or the basic question on react is what is reactjs to answer this question I would say reactjs is an open-source frontend JavaScript library which is used to build user interfaces and handle view layer for web and mobile applications it follows a component based approach the react package contains only the functionality necessary to Define react components and it is typically used together with a react renderer like react Dom for the web or react native for the native environment now here when I talk about component based approach so everything in reactjs is a component so what happens is these components can be reused they can be placed wherever required so we can just write it once and use it anywhere and any time now even though react was open sourced only in 2015 it has one of the largest communities supporting it moving to the second question that is what are the features of reactjs to answer this question I would say the major three features of reacts JS because of which reactjs is known are virtual Dom server side rendering and unidirectional data flow or data binding it’s talking about the virtual Dom that is actually the virtual data object model a virtual Dom is a lightweight JavaScript object which originally is just a copy of the real Dom it is a node tree that lists the elements their attributes and content as objects and their properties reacts render function creates a not tree out of the react components it then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system talking about the serers side rendering when I say serers side rendering which means using a server to generate HTML from JS modules in response to a URL request that’s in contrast to client side rendering which uses the browser to create HTML using the Dom server side rendering with JS or react Works similarly to other server side languages now when I say unit directional data flow data binding so in react data flows in a single direction that is from parent components to child components which helps in data binding and it makes the application and the code predictable and more debuggable moving ahead with the next question which asks list some of the major advantages of react talking about the advantages of react so it increases the application’s performance it can be conveniently used on the client as well as server side because of jsx cod’s readability increases and react is easy to integrate with other Frameworks like meteor angular Etc and using react writing UI test cases becomes extremely easy now let’s move ahead to the next question which asks what are the limitations of react talking about the limitations of react react is just a library not a full-blown framework and its library is very large and takes time to understand it can be a little difficult for the Novis programmers to understand and coding gets a little complex as it uses inline templating and jsx now the next question is what is jsx so jsx is basically shorthand for JavaScript XML this is a type of file used by react which utilizes the expressiveness of JavaScript along with HTML like template syntax this makes the HTML file really easy to understand and this file makes applications robust and boost boost its performance now let’s see the next question which is what do you understand by virtual dor explain its working so as we have discussed in a previous question also about virtual domor a virtual domor is a lightweight JavaScript object which is just the copy of the real Dom it is a notary that lists the elements their attributes and content as objects and their properties react’s render function creates a not Tre out of the react components it then Updates this tree in respon responds to the mutations in the data model which is caused by various actions done by user or by the system and this virtual Dom Works in three simple steps which are whenever any underlying data changes the entire UI is rendered in Virtual Dom representation then the difference between the previous Dom representation and the new one is calculated and once the calculations are done the real Dom will be updated only with the things that have actually changed so here a kind of patch work is done as you can see in the picture also moving ahead with the next question that is differentiate between real Dom and virtual Dom when we compare real Dom and virtual Dom we find the differences like real Dom updates slow while virtual Dom updates faster real Dom can directly update HTML while virtual Dom can’t directly update HTML real Dom creates a new Dom if element updates while virtual Dom updates the GSX if element updates so that’s why real Dom is comparatively slower than the virtual Dom because in real Dom every time any element gets updated a new Dom is created while with react which uses virtual Dom whenever any element gets updated only the js6 part gets updated now the next difference is Dom manipulation is very expensive in real Dom because every time you have to create the new Dom while Dom manipulation in react that is virtual Dom is very easy and real Dom results into too much of memory wastage while virtual Dom results in no memory wastage at all the reason we know because every time new Dom is created whenever any element gets updated while with the help of virtual Dom in react only the GSX part gets updated with the update in any element now moving to the next question which asks why can’t browsers read GSX browsers can only read JavaScript objects but jsx is not a regular JavaScript object thus to enable a browser to read jsx first we need to transform jsx file into a JavaScript object using jsx Transformers like Babel and then pass it to the browser now let’s move ahead with the next question that is what is jsx transform as browsers don’t support GSX the compilers like Babel or typescript are used to transform GSX into regular Javas script object which is understood by the browsers as we have seen in the previous question now jsx transform automatically compiles the jsx source code without having to rely upon the typical compilers with the new transform jsx can be used without importing react and according to the setup its compiled output slightly improves the bundle size as well now let’s see the answer for the next question which is how react syntax changed from es5 to es6 so as you can see on the screen the code snipp it for es5 and es6 so in es5 we use react. create class and which we initialize in a variable for example here we have taken my component but in es6 we just make use of classes and we make use of extend keyword and the syntax is class the name of the component my component or the class my component extends react. component so the major difference between es6 and es5 is in es5 we make use of create class while in es6 we make use of react. component now let’s move ahead with the next question that is how errors are handled in react so talking about the error handling in react the most distinctive and react specific type of error handling is what is known as error boundaries so error boundaries are react components that catch JavaScript errors anywhere in their child component tree log those errors and display a fallback UI instead of the component tree that crashed error boundaries catch errors during rendering in life cycle methods and in Constructors of the whole tree below them now let’s see the next question that is what are the limitations of error boundaries in react so talking about the limitations of error boundaries error boundaries do not catch errors for event handlers asynchronous code that is set a timeout or request anim frame callbacks for server side rendering and errors thrown in the error boundary itself rather than its children now let’s see the next question that is what are the features introduced in es7 so ecma is script 2016 or es7 introduced two new features that are array.prototype do includes function and the second one is exponentiation operator talking about array.prototype do includes function so it checks the array for the value passed as an argument it returns true if the array contains the value otherwise it returns false earlier we needed to use array. prototype. index of function to check if the given array contains an element or not talking about exponentiation operator so ecma script 2016 or es7 introduced the exponentiation operator that is double Aster it has the same purpose as math. power function it Returns the first argument raised to the power of the second argument moving to the next question which asks list some of the features of es10 so this is the latest version of ecma script so the features introduced in es10 include optional cach binding object. from entries array. flat function array. flat map function Dynamic import Global this object now the next question is how is react different from angular so talking about the differences between react and angular we see on the basis of architecture react is only the view of MVC that is model view controller while angular is complete framework for MVC that is model view and controller talking about the rendering so react supports server side rendering while angular supports client side rendering talking about the Dom that is data object model so as we have seen earlier also react uses virtual D and we have seen the advantages of using virtual Dom while angular uses the real Dom talking about the data binding react uses oneway data binding or the unidirectional data flow while angular has two-way data binding or the bir directional data flow talking about the debugging react supports compile time debugging while angular supports runtime debugging and talking about the author or who owns react and angular so react is owned by Facebook while the author of angular is Google with this we have seen some of the frequently asked questions and answers based on General react now moving ahead let’s see the questions based on react GS components so starting with the first question based on reacts components what do you understand from in react everything is a component to answer this question I would say components are the building blocks of a react application UI so everything in react is a component and these components split up the entire UI into small independent and reusable pieces then it renders each of these components independent of each other without affecting the rest of the UI and these components can be JavaScript functions which takes in arbitrary inputs and returns HTML representation now let’s see the next question which asks what is the purpose of render function in react or explain the purp purpose of render function in react to answer this question I would say each react component must have a render function mandatorily it returns a single react element which is the representation of the Native Dom component if more than one HTML element needs to be rendered then they must be grouped together inside one enclosing tag such as form group div Etc this function must be kept pure that is it must return the same result each time it is invoked moving to the next question that is how can you embed two components into one so as you can see on the screen we have one code snippet we have embedded two components with the help of class then the component name or the class name then using the keyword extends and we made the use of react. component with this syntax as you can see on the screen we are embedding two components into one so there are two components the my component and header component moving to the next question that asks what are props in react so Props is basically the Shand for properties in react they are readon components which must be kept pure that is immutable and they are always passed down from the parent to the child components throughout the application a child component can never send a prop back to the parent component and this helps in maintaining the unidirectional data flow or the data binding and are generally used to render the dynamically generated data moving to the next question what is a state in react and how it is used talking about the states so states are the heart of react components states are the source of data and must be kept as simple as possible basically states are the objects which determine components rendering and behavior they are mutable unlike the props and create Dynamic and interactive components and they are accessed via this do state function moving to the next question which is differentiate between State and props so while comparing State and props we find the differences like in state and prop both receive initial value from parent component while in state parent component cannot change value while with the help of prop parent component can change the value and we can set default values inside the components both in state as well as in props in state we can make changes inside the component but with props we cannot make the changes inside the component and we can set initial values for child components in both state as well as in props but changes inside the child components cannot be made in state while in prop we can make the changes inside child components now moving to the next question which asks how can you update state of a component now here you can see a code snippet so basically the answer for this question is we can change the state or we can update the state of a component by making the use of this do set State function and as you can see on the code snippet as well earlier here name was Max and ID was 101 then again in render function we’ll make use of set State basically this do set State function and inside that we can change the value or we can update the state of the component so here we are making the change in the value as you can see over here we are updating it to jaha and id2 triple2 now moving to the next question that is should we update the state directly so to answer this question we should not update the state directly and why we should not update the state directly because if we update the state directly calling the set State function afterward we just replace the update we made made and when we directly update the state it does not change this do state immediately instead it creates a pending State transition and accessing it after calling this method will only return the present value and we will lose control of the state across all the components so that’s why we should not update the state directly moving to the next question that is what is Arrow function and how it is used Arrow functions are more of brief Syntax for writing that function expression they are also called fat Arrow the functions it is symbolized with equal to and greater than symbol now these functions allow to bind the context of the components properly since in es6 Auto binding is not available by default and arrow functions are mostly useful while working with the higher order functions or HFS as you can see in the picture as well without Arrow function and with arrow function without Arrow function we were making use of this do handle change. bind while with aror function we have just made use of this symbol that is equal to and greater than and then we made use of this dot handle on change no need for bind and all now moving to the next question that is how do you reference a Dom element it is a pretty simple question and answer to this question is also very simple and crisp that is an object this do refs that is this do RFS which is found as an instance inside the component can be used to access Dom elements in reactjs now moving to the next question that is what is the use of e do persist function answer of this question is nothing e persist function does nothing because e do persist function was used in event pooling but with react 17 event pooling has been completely removed but this e do persist function is still available on the react event object but now it doesn’t do anything now moving to the next question which asks what do you mean by event pooling as we have seen in the previous question that event pooling has been removed from react 17 but we should know what is event pooling because this question has been frequently Asked in interviews so the synthetic event objects were pulled this means that the synthetic event object would be reused and all properties would be nullified after the event handler has been called now for example you can see the code Snippets available here so earlier when event pulling was supported in react the first snippet as you can see over here this would not work because the event object gets reused but with the help of e do persist function this code works because it prevents react from resetting its properties but this is the case before react 17 now event pooling is not supported by react now moving to the next question what are react hooks so react hooks are functions that let us hook into react State and life cycle features from a functional component so what is this hook into actually these functions let us use the react State and life cycle features from a functional component and react hooks Cann not be used in class components they let us write components without the class now moving to the next question question when and why hooks were introduced in react react hooks were introduced in the 16.8 version of react or react 16.8 earlier functional components were called stateless components and only class components were used for State Management and life cycle methods the need to change a functional component to a class component whenever State Management or life cycle methods were to be used led to the development of hooks now moving to to the next question that is do you know any of the techniques to optimize react app performance so there are many techniques to optimize react app performance but some of them are using use memo function using react. pure component and maintaining state collocation so when I say using use memo function so it is a react hook that is used for caching CPU expensive functions sometimes in a react app a CPU expensive function gets called repeatedly due to reenders of a component which can lead to slow rendering now this use memo function who can be used to cat such functions by using use memo the CPU expensive function gets called only when it is needed talking about using react. pure component so it is a base component class that checks the state and props of a component to know whether the component should be updated instead of using the simple react. component we can use react. pure component to reduce the reenders of a component unnecessarily and ultimately it optimizes the application performance and when I say maintaining state collocation so this is the process of moving the state as close to where we need it as possible sometimes in react application we have a lot of unnecessary States inside the parent component which makes the code less readable and harder to maintain not to forget having many states inside a single comp component leads to unnecessary reenders for the component and it is better to shift states which are less valuable to the parent component to a separate component now moving to the next question what is lazy loading lazy loading is the feature introduced in react version 16.6 which allows for some components to load later than the other components this way we can load the components which are fast like text earlier and the components which load later like images later it is also Al referred to as code splitting and data fetching moving to the next question what is a fragment in react a common pattern in react is for a component to return multiple elements but fragments let us group a list of children without adding extra nodes to the Dom while rendering multiple elements will require a div tag around the content as the render method will only render a single root node inside it at a time so in react 16.2 fragment were introduced and we use them instead of extra div tags and all so as you can see in the code snippet available on the screen in place of using div tag we are just making use of react. fragment and inside this you can see this child a child B CH see these are basically the elements now moving to the next question which asks what is set State function so set State function allows us to change state in a react class component as we have seen in a previous this question we were making use of this do set State function right and the set State function enqs change to the component State and tell react that this component and its children need to be rendered with the updated State this is the primary method you should use to update the UI and set a state does not always update the component immediately instead it may defer the update until later for better performance and the Syntax for this function as we have seen in the previous question also here set State and in the braces we can give the updator or the call back we can pass it as the argument moving to the next question that is what is use State function so the use State function is a react hook that allows to have a state variables in functional components the use State Hook is a special function that takes the initial State as an argument and returns an array of two entries moving to the next question what do you mean by Contex in react so the react context API is a way for a react app to effectively produce Global variables that can be passed around this is the alternative to prop drilling or moving props from grandparent to child to parent and so on a new type of context can be created using react. Create context API and this context API is added in version 16.3 of react that allows one to share state across the entire application or part of it lightly with ease moving to the next question what do you mean by prop drilling so prop drilling can be defined as a process and react application where props are passed from one part of a tree to another by going through other parts that do not need the data but only help in passing it through the tree and it is also known as prop threading now I give it over to Mr asho to take you through the more questions on react components react Redux and react router what are the differences between State full and stateless components this table is showing the differences so stateful components are those which stores information about component State change in memory stess they calculates the internal state of the components stateful components they have authority to change the state as the name suggest stateless components cannot have authority they do not have authority to change the state if I talk about stateful component they contains the knowledge of past current and possible future changes in state stateless components they contains no knowledge of past current and possible future State changes stateless components notifies them about the requirement of the state change then they send down the props to them stateless component if I talk about they receive the props from the stateful components and treat them as call back functions so this table is very important it’s a very general question again asked nowadays in reactjs interviews that what is the difference between stateful and stateless components what are the different phases of react component life cycle in a very interesting one so as we all know that there are four phases so here I’m defecting the three phases and initial phase which are mostly used the updating phase one is the mounting phase and another one is the unmounting phase we can amalgamate the two in one so now it becomes three so initial phase updating phasee and unmounting phase as you can see on the screen every phase is having their own methods which are working in a particular order or this particular priorities so initial phase is having the function as get default props get initial State component will Mount render and component did Mount if I talk about updating phase these are the methods or functions available in the updating phase again it is had render if I talk about the unmounting phase so unmounting phase has a function called components will unmount so these are the various life cycle methods I will say these are called the life cycle methods in reactjs which we need to have so that whatever props or components we are using they gets mounted and unmounted accordingly explain the life cycle methods of react components in detail if I talk about the life cycle methods which we just saw in the previous slide that what are the life cycle methods in react so these are the various methods which we generally use component will mount it gets executed just before the rendering both on client and server side component did Mount it is executed after first render only on the client side the other one is component will receive props it is invoked as soon as the props are received from parent class before another render is called the other method or the life cycle method is should component update it returns true or false value based on certain conditions if you want your component to update return true else return false by default its value is false component will update it is called just before rendering takes place component did update and the other one is component will unmount this is called after the component is unmounted from the top it is used to clear up the memory spaces so all these are the life cycle methods which are used in react JS now what is a event in react events are triggered reactions or I will say actions to specific actions like Mouse over Mouse click key press Etc react events are similar to HTML JavaScript events so for example in this example or in this diagram as you can see this is a bulb is there is an action called switch on if someone clicks on on the bulb is getting on so this is kind of a event which is getting triggered which are reactions to specific actions how we can create events in react JS so as you can see here this is a render function class display extends react. component in es6 class standard of writing the code here I’m using a render function which is returning a TI and on click is the event that is how we can create the events in react CHS this. show click me what are synthetic events in react CH synthetic events are uh the cross browser wrappers around the browser’s native event system they combines the browser Behavior into one API and they’re done to ensure events have consistent properties across different browsers so if we want to have a react JS application running on different browsers we will use synthetic events in react JS what do you understand by reps which are references in react JS so reps stands for references so they are used to return references to a particular element or component returned by render they are basically useful when we need Dom measurements or to add methods to the components list some of the cases when you should use reps so first of all they are used to manage Focus text selection or media playback for triggering imperative animations just like as you can see on the screen if you want to display this kind of Animation imperative animation we will use reps in reactjs and if you want to integrate with third party Dom libraries that is also where we use reps in react JS how do you modularize code in react so we can modelize code uh by using the export and import standard or by using export and import properties we can write the component separately in different files so for one file we will use the export property and for another file we can use the import property that is how you can modelize the reactjs code and as you can see on the screen the two code is snippits for or two files I’ll say for export and import properties how forms are created in react this is again a very basic question questions with interview question with respect to react so HTML form elements maintain their own State and regular Dom and update themselves based on user input in reactjs state is contained in the state property of the component and uh it gets only updated bya set State as we all know so JavaScript function is used for handling the form submission what do you know about controlled and uncontrolled components so as I mentioned earlier components are of two type presentational components and container comp components again there are two other types of components which are controlled and uncontrolled so controlled components are those which do not maintain their own State the state is not maintained in control components data is controlled by parent component not by the child components the control components takes in current value through props and notifies changes via call packs I talk about uncontrolled components they maintain their own State data is controlled by Dom and reps are used to get their current value so if you want to use rest we need to have uncontrolled components now what are H when I say h these are high order components so these are the custom components I will say which we develop while doing programming in reactjs so these are the custom components which wraps another component they accept dynamically provided child components then they do not modify the input component they do not copy any behavior from the input component and I’ll say that these are the pure functions basically they are the custom components which are developed to addon functionality to some other components these are called H’s so what can you do with h h means high order components can uh reuse the code logic and bootst step abstraction using H’s we can render High checking State abstraction manipulations and also we can also do state and props manipulations with h high order components now what are pure components pure components are the simplest fastest components which we can right these are very fast they can replace any component that only has render answers the Simplicity and performance of the application these are the pure components as you can see here there is a code snippet react dom. render H1 hello document. get element by ID content so these are the two parameter which needs to be passed to the render function and this is the simple component I will say simplest component or I can say the pure components which we can write in reactjs and Hance the performance and it I will it is the fastest in react CHS now what is the significance of keys in react chairs or what is the significance of keys in react it is used to identify unique virtual Dom elements with their corresponding data driving the UI so as we all know there is a key value pair combination always in every programming language just like that we have keys and reactj which is used to identify the virtual Dom elements and what are the virtual Dom elements with respect to their driving UI this we can know using keys in react CHS they must be unique number or a string they helps react to optimize rendering by recycling existing Dom elements so instead of rendering with keys react just reorders the element so if you don’t want to reender your UI or if you don’t want to reender your components you can just reorder the elements using keys in react CHS and obviously with all these T the performance of the application gets optimized and highly increased in react ch so that was all about the second section of the react interview question let’s move forward and now I will talk about the interview questions related to react Redux this is a combination of react and Redux technology so what were the major problem with MVC framework see we all know it’s a model view controller so what is the major problem so Dom manipulation is very expensive because MVC framework is completely based on Dom and not on Virtual Dom just like in react CHS is slow and inefficient there is lot of memory wastage in MVC framework because of circular dependency complicated model was created around model and Views so these are some of the drawbacks or problems with MVC framework now flux before Redux there was a technology called flux which was introduced by Facebook so what was flux architectural pattern that enforces unidirectional data flow so on the screen as you can see there is a action then dispatcher store and view so architectural pattern that enforces unidirectional data flow controls derive data and enables communication between multiple components now as you can see there is a central store which has Authority for all the data any update in data must occur here only so store is the central or the heart for all react Redux or flux application it provides stability to the application and it reduces runtime errors what is Redux Redux is one of the hottest Library I will say for frontend development it is very very famous you can also check how much it is famous and its popularity on GitHub sites that it has more number of stars and more number of watches as compared to flux it’s aable state container for JavaScript apps it is mostly used for State Management applications where State needs to be managed uh applications developed with Redux are easy to test and it helps to write applications that behave consistently and can run in different envir en Ms what are the three principles that Redux follows first is a single source of truth that is the store single source of Truth and when I say I’m talking about here the single store there is only one store in a Redux or react Redux application state is read only in Redux the changes are made with pure functions you can make changes only with the pure functions in Redux libraries what do you understand by single source of truth when I say single source of Truth it is the store which I’m talking about in Redux application Redux uses a store for storing all the application State at one place whatever the state happening or state changes happening in a react Redux application it will be notified to store or will happen uh in conjunction with a store so component state is stored in the store and they receive updates from the store itself so whatever the components so these are the various components so the state of all these components will be stored in a single place which is called store and any update needs to happen or needs to be there that will be received from the store itself the single state tree makes it easier because it’s a single state tree makes it easier to keep track of the changes over time and debug or inspect the application what are the various components of Redux first one is the action which is an object that describe what happen happened reducer it is a place to determine how the state will change or I will say the reducers are the pure functions which ISS how it needs to be done as I said action that what needs to be done reducer how it needs to be done is given by the reducers because these are the pure functions store as you saw just now in the previous slide that store is a single source of truth then need to be a single store which is used for State Management of all the components so a state object of the entire application is saved in the store view is to Simply displays the data provided by the store so how the data flows through Redux again a very interesting question that how we should know that how data is flowing through Redux so as you can see here that these are the container components which is passing data as the props they are passing the data to actions action is passing the data to reducer so the input for the store is the reducer and reducer is again giving the data to the provider component or you can say the view part of it so that is how the data Flows In Redux applications how actions are defined in Redux always remember that action should have a type property that indicates the type of action which needs to be performed so type is very important for every action so let’s say in this code is snip it as you can see on the screen there is a function called add to which is taking the input parameter as text is what it is returning is it is a type and this what type of action it is act to do so they must be defined as a string constant and we can add more properties to it that is not a problem with the action you can add as many properties as you want but the most mandatory part or the most important part for an action is it needs to have a type property and actions are created using functions called action creators the other question which we have is what is the role of reducers reducers are the pure functions which specify how the application State changes in response to an action it takes in the previous state and then action and Returns the new state so what is the work of a reducer basically it takes the previous state make the changes and it Returns the new state it determine what sort of update needs to be done based on the type of action and Returns the new values it Returns the previous state if no work needs to be done if there are no changes in the state or if there are no updates of obviously it will return the previous state which it takes as a input and as output it returns a new state with the changed parameters what is the significance of a store in Redux store as we all know now that store is the single source of Truth a JavaScript object holds the application state it maintains the application or I can say it maintains the state tree of the particular application that is the store provides a helper methods to access the state dispatch ction and register listeners with store the data State can be synchronized from the server level to the client CER without much hle and since it’s a single store it’s a single source of truth it’s a single place to maintain the state tree of the application it makes the development of the large application very easy and fast how Redux is different from flux so these are the basic differences between flux and Redux I talk about flux the store contains State and change log has multiple stores flat disconnected stores inlux all the stores are disconnected single turn dispatcher react component subscribed to the store in flux state is mutable so you can change the state in flux if I talk about Redux store and change logic are separate we have a single store in Redux single store with hierarchical reducers you can have multiple reduc ERS in Redux but the store needs to be single in react Redux application so if I talk about the container components they utilize connect and state is immutable this is again very important that the state is immutable in react Redux application what are the advantages of reduct so I’ve list down some of the advantages of Redux predictability maintainability the application will be very fast it will be optimized we have many developer tools the testing and debugging part will be easy and huge open source Community for Redux is available out there on internet and precise organization of course because there is only one store which is maintaining the state complete state of the application so these are some of the advantages of Redux which makes react Redux application very famous and very popular and the next question in react Redux is what is Redux tun so Redux tun is a middleware that lets call Action ction creators that return a function instead of an action object that function receives a stores dispatch method which is then used to dispatch regular synchronous actions inside the body of the function once the asynchronous operations have completed and the tongue can be used to delay the dispatch of an action or to dispatch only if a certain condition is met and basically it sits between action Creator and reducer in the react Redux flow now moving to the last part of the last section of this webinar that is the react router interview questions what is react router it’s a very powerful routing Library I’ll say it helps in adding new screens and flows to the application it keeps the URL in sync with data that is being displayed on the web page and it is a very simple API the react router API are very simple to use why switch keyword is used in react router version 4 the switch keyword is used when you want to display only a single route to be rendered among several defined routs so as you can see here if I want to have multiple defined Roots but I want to display only a single root then I use the switch statement why do we need a router in react so router helps in defining multiple routs inside the router with each route leading to a unique view as you can see on the screen there are multiple react routers for example these are the three router and each router is leading or representing I will say a unique view so that is why we need a router in react list down the advantages of react router so there are various advantage of react router the API is very simple and the API is all about component the API is component based the router apis it can be visualized the single root component no need to manually set history value it has separate packages for web and Native platforms that’s very famous how react router is different from conventional routing of data so again there’s a table of the differences based on the various topics Pages involved each view corresponds to a new file in react router only single HTML page is involved in conventional routing we used to have multiple PES involved in application if I talk about the URL changes in conventional routing HTP request is sent to the server and corresponding HTML page is received in react router only the history attribute is changed this is a very drastic change in the uh request response terminologies if I talk about the look and feel user actually navigates across different pages for each view in conventional routing but for react router user is duped thinking he’s navigating across different pages but it is actually not the case now the next question is why is switch keyword used in react router V5 or version 5 although a div tag is used to encapsulate multiple Roots inside the router the switch keyword is used when we want to display only a single route to be rendered amongst the several defined Roots the switch tab when in use matches the typed URL with the defined roots in sequential order when the first match is found it renders the specified value and thereby bypassing the remaining Roots as we have seen some of the frequently asked questions and answers in react interviews now let’s have a look on the requirements or the skills required to become a reactjs developer so to become a reactjs developer you should have the following skills which include fundamentals of HTML CSS and JavaScript fundamentals of reactjs which includes jsx es6 hooks node plus npm and Redux and with this we come to an end to this react GS full course and if you enjoyed listening to this full course please be kind enough to like it and you can comment on any of your doubts and queries we will reply to them at the earliest do look up for more videos and playlist And subscribe to the ureas YouTube channel to learn more thank you for watching and happy learning

By Amjad Izhar
Contact: amjad.izhar@gmail.com
https://amjadizhar.blog
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!

Leave a comment