React
React
React Is A Declarative, Efficient, Flexible Open Source Front-End JavaScript Library Developed By
Facebook In 2011. It Follows The Component-Based Approach For Building Reusable UI Components,
Especially For Single Page Application. It Is Used For Developing Interactive View Layer Of Web And
Mobile Apps. It Was Created By Jordan Walke, A Software Engineer At Facebook. It Was Initially
Deployed On Facebook's News Feed Section In 2011 And Later Used In Its Products Like WhatsApp &
Instagram.
React Uses Virtual DOM. Below Is The Difference Real And Virtual DOM.
REAL DOM
1. It Updates Slow.
VIRTUAL DOM
1. It Updates Faster.
5. No Memory Wastage.
React Framework Gaining Quick Popularity As The Best Framework Among Web Developers. The
Main Features Of React Are:
1. JSX
2. Components
4. Virtual DOM
5. Simplicity
6. Performance
1. Reusable Components
2. Performance Enhancement
- View Part
Q.What Is JSX?
JSX Is A 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. This File Makes Applications Robust And Boosts Its Performance.
Browsers Can Only Read JavaScript Objects But JSX In 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.
ARCHITECTURE - React Have Only The View Of MVC Where Angular Have Complete MVC
RENDERING - React Have Server-Side Rendering Where Angular Have Client-Side Rendering
DOM - React Uses Virtual DOM Where Angular Uses Real DOM
DATA BINDING - React Have One-Way Data Binding Where Angular Have Two-Way Data Binding
DEBUGGING - React Have Compile Time Debugging Where Angular Have Runtime Debugging
TYPE - React Is Open Source JS Framework Where Angular Is Open Source MVC Framework
TESTING - React Support Unit Testing Where Angular Support Unit And Integration Testing
Q.Explain The Purpose Of Render() In React.
Each React Component Must Have A Render() 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 I.E., It Must Return The Same Result Each Time It Is
Invoked.
Q.What Is Props?
- Props Is The Shorthand For Properties In React. They Are Read-Only Components Which Must Be
Kept Pure I.E. Immutable. 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. This Help In Maintaining The Unidirectional Data Flow And Are Generally Used To
Render The Dynamically Generated Data.
- 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.
They Are Accessed Via This.State().
States
Props
- Arrow Functions Are More Of Brief Syntax For Writing The Function Expression. They Are Also
Called ‘Fat Arrow‘ (=>) The Functions. These Functions Allow To Bind The Context Of The
Components Properly Since In ES6 Auto Binding Is Not Available By Default. Arrow Functions Are
Mostly Useful While Working With The Higher Order Functions.
Stateful Component
- Contains The Knowledge Of Past, Current And Possible Future Changes In State
- Stateless Components Notify Them About The Requirement Of The State Change, Then They Send
Down The Props To Them.
Stateless Component
- They Receive The Props From The Stateful Components And Treat Them As Callback Functions.
- Initial Rendering Phase: This Is The Phase When The Component Is About To Start Its Life Journey
And Make Its Way To The DOM.
- Updating Phase: Once The Component Gets Added To The DOM, It Can Potentially Update And Re-
Render Only When A Prop Or State Change Occurs. That Happens Only In This Phase.
- Unmounting Phase: This Is The Final Phase Of A Component’s Life Cycle In Which The Component Is
Destroyed And Removed From The DOM.
- ComponentWillMount() – Executed Just Before Rendering Takes Place Both On The Client As Well
As Server-Side.
- ComponentDidMount() – Executed On The Client Side Only After The First Render
- ComponentWillReceiveProps() – Invoked As Soon As The Props Are Received From The Parent Class
And Before Another Render Is Called.
- ComponentWillUnmount() – Called After The Component Is Unmounted From The DOM. It Is Used
To Clear Up The Memory Spaces.
Q.What Is An Event In React?
In React, Events Are The Triggered Reactions To Specific Actions Like Mouse Hover, Mouse Click, Key
Press, Etc.But There Are Some Syntactical Differences Like:
- Events Are Named Using Camel Case Instead Of Just Using The Lowercase.
Refs Is The Short Hand For References In React. It Is An Attribute Which Helps To Store A Reference
To A Particular React Element Or Component, Which Will Be Returned By The Components Render
Configuration Function. It Is Used To Return References To A Particular Element Or Component
Returned By Render(). They Come In Handy When We Need DOM Measurements Or To Add
Methods To The Components.
- A Higher-Order Component (HOC) Is A Function That Takes A Component And Returns A New
Component. Basically, It’s A Pattern That Is Derived From React’s Compositional Nature We Call
Them As “Pure’ Components” Because They Can Accept Any Dynamically Provided Child Component
But They Won’t Modify Or Copy Any Behavior From Their Input Components.HOC Can Be Used For
Many Use Cases As Below,
- Props Manipulation
- Hooks Are A New Addition In React 16.8. They Let You Use State And Other React Features Without
Writing A Class. With Hooks, You Can Extract Stateful Logic From A Component So It Can Be Tested
Independently And Reused. Hooks Allow You To Reuse Stateful Logic Without Changing Your
Component Hierarchy. This Makes It Easy To Share Hooks Among Many Components Or With The
Communit
- Primarily, Hooks In General Enable The Extraction And Reuse Of Stateful Logic That Is Common
Across Multiple Components Without The Burden Of Higher Order Components Or Render Props.
Hooks Allow To Easily Manipulate The State Of Our Functional Component Without Needing To
Convert Them Into Class Components. Hooks Don’t Work Inside Classes (Because They Let You Use
React Without Classes). By Using Them, We Can Totally Avoid Using Lifecycle Methods, Such As
ComponentDidMount, ComponentDidUpdate, ComponentWillUnmount. Instead, We Will Use Built-
In Hooks Like UseEffec
UseState Is One Of Build-In React Hooks. UseState(0) Returns A Tuple Where The First Parameter
Count Is The Current State Of The Counter And SetCounter Is The Method That Will Allow Us To
Update The Counter's State.
We Can Use The SetCounter Method To Update The State Of Count Anywhere - In This Case We Are
Using It Inside Of The SetCount Function Where We Can Do More Things; The Idea With Hooks Is
That We Are Able To Keep Our Code More Functional And Avoid Class Based Components If Not
Desired/Need
Q.What Is Npm
Npm (Short For Node.Js Package Manager) Is A Package Manager For The JavaScript Programming
Language. It Is The Default Package Manager For The JavaScript Runtime Environment Node.Js. It
Consists Of A Command Line Client, Also Called Npm, And An Online Database Of Public And Paid-
For Private Packages, Called The Npm Registry. The Registry Is Accessed Via The Client, And The
Available Packages Can Be Browsed And Searched Via The Npm Website. The Package Manager And
The Registry Are Managed By Npm, Inc.
Q.What Is Node.JS
React's StrictMode Is Sort Of A Helper Component That Will Help You Write Better React
Components, You Can Wrap A Set Of Components With And It'll Basically:
- Verify That The Components Inside Are Following Some Of The Recommended Practices And Warn
You If Not In The Console.
- Verify The Deprecated Methods Are Not Being Used, And If They're Used Strict Mode Will Warn
You In The Console.
- When Building A React Application, There Is Often The Need For A Deeply Nested Component To
Use Data Provided By Another Component That Is Much Higher In The Hierarchy. The Simplest
Approach Is To Simply Pass A Prop From Each Component To The Next In The Hierarchy From The
Source Component To The Deeply Nested Component. This Is Called Prop Drilling.
- To Avoid Prop Drilling, A Common Approach Is To Use React Context. This Allows A Provider
Component That Supplies Data To Be Defined, And Allows Nested Components To Consume Context
Data Via Either A Consumer Component Or A UseContext Hook.
Controlled
- It Does Not Maintain Its Internal State.
Uncontrolled
- Context Allows Passing Data Through The Component Tree Without Passing Props Down Manually
At Every Level. In React Application, We Passed Data In A Top-Down Approach Via Props. Sometimes
It Is Inconvenient For Certain Types Of Props That Are Required By Many Components In The React
Application. Context Provides A Way To Pass Values Between Components Without Explicitly Passing
A Prop Through Every Level Of The Component Tree.
- A Map Is A Data Collection Type Where Data Is Stored In The Form Of Pairs. It Contains A Unique
Key. The Value Stored In The Map Must Be Mapped To The Key. We Cannot Store A Duplicate Pair In
The Map(). It Is Because Of The Uniqueness Of Each Stored Key. It Is Mainly Used For Fast Searching
And Looking Up Data.
- In React, We Can Create Multiple Components Which Encapsulate Behavior That We Need. After
That, We Can Render Them Depending On Some Conditions Or The State Of Our Application. In
Other Words, Based On One Or Several Conditions, A Component Decides Which Elements It Will
Return. In React, Conditional Rendering Works The Same Way As The Conditions Work In JavaScript.
We Use JavaScript Operators To Create Elements Representing The Current State, And Then React
Component Update The UI To Match Them.
- There Is More Than One Way To Do Conditional Rendering In React. They Are Given Below
- If, Ternary Operator, Logical && Operator, Switch Case Operator, Conditional Rendering With
Enums
- React Router Plays An Important Role To Display Multiple Views In A Single Page Application. It Is
Used To Define Multiple Routes In The App. 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 Route. So, We Need To Add A Router Library To The React App, Which Allows Creating
Multiple Routes With Each Leading To Us A Unique View.
Conventional Routing
- The HTTP Request Is Sent To A Server To Receive The Corresponding HTML Page.
- In This, The User Navigates Across Different Pages For Each View.
React Routing
- In This, The User Is Thinking He Is Navigating Across Different Pages, But Its An Illusion Only.
- 'Switch' Keyword Is Used To Display Only A Single Route To Rendered Amongst The Several Defined
Routes. The Component Is Used To Render Components Only When The Path Will Be Matched.
Otherwise, It Returns To The Not Found Component.
Q.What Is Redux?
- Redux Is An Open-Source JavaScript Library Used To Manage Application State. React Uses Redux
For Building The User Interface. The Redux Application Is Easy To Test And Can Run In Different
Environments Showing Consistent Behavior. It Was First Introduced By Dan Abramov And Andrew
Clark In 2015.
- React Redux Is The Official React Binding For Redux. It Allows React Components To Read Data
From A Redux Store, And Dispatch Actions To The Store To Update Data. Redux Helps Apps To Scale
By Providing A Sensible Way To Manage State Through A Unidirectional Data Flow Model. React
Redux Is Conceptually Simple. It Subscribes To The Redux Store, Checks To See If The Data Which
Your Component Wants Have Changed, And Re-Renders Your Componen
- Single Source Of Truth: The State Of Your Entire Application Is Stored In An Object/State Tree Inside
A Single Store. The Single State Tree Makes It Easier To Keep Changes Over Time. It Also Makes It
Easier To Debug Or Inspect The Application.
- The State Is Read-Only: There Is Only One Way To Change The State Is To Emit An Action, An Object
Describing What Happened. This Principle Ensures That Neither The Views Nor The Network
Callbacks Can Write Directly To The State.
- Changes Are Made With Pure Functions: To Specify How Actions Transform The State Tree, You
Need To Write Reducers (Pure Functions). Pure Functions Take The Previous State And Action As A
Parameter And Return A New State.
Q.List Down The Components Of Redux.
- STORE: A Store Is A Place Where The Entire State Of Your Application Lists. It Is Like A Brain
Responsible For All Moving Parts In Redux.
- Reducers Read The Payloads From The Actions And Then Updates The Store Via The State
Accordingly. It Is A Pure Function Which Returns A New State From The Initial State. It Returns The
Previous State As It Is If No Work Needs To Be Done.
- A Store Is An Object Which Holds The Application's State And Provides Methods To Access The
State, Dispatch Actions And Register Listeners Via Subscribe(Listener). The Entire State Tree Of An
Application Is Saved In A Single Store Which Makes The Redux Simple And Predictable. We Can Pass
Middleware To The Store Which Handles The Processing Of Data As Well As Keep A Log Of Various
Actions That Change The Store's State. All The Actions Return A New State Via Reducers.
- Better Code Organization – Redux Is Precise In Terms Of How The Code Needs To Be Organized.
This Results In A Consistent Code Workable For Any Development Team.
- Developer Tools – Allow Developers To Track Each And Everything, Ranging From Actions To State
Changes, Happening In The Application In Real-Time
- Easy Testing – Redux Code Is Mainly Composed Of Functions That Are Isolated, Pure, And Small.
Hence, Testing Is Much Easy And Simple
- Maintainability – Thanks To A Predictable Outcome And Strict Structure, The Code Is Easier To
Maintain.
- Output Predictability – There Is No Confusion About Syncing The Current State With Actions As
Well As Other Parts Of The Application As There Is Only A Single Source Of Truth, Which Is The Store
- Server-Side Rendering – There Is A Need Of Only Passing The Store Created On The Server-Side To
The Client-Side. In Addition To This Being Useful For Initial Render, It Also Offers A Better User
Experience Because It Optimizes The Application Performance
- Redux DevTools Is A Live-Editing Time Travel Environment For Redux With Hot Reloading, Action
Replay, And Customizable UI. If You Don’t Want To Bother With Installing Redux DevTools And
Integrating It Into Your Project, Consider Using Redux DevTools Extension For Chrome And Firefo
- Also, React Redux Uses Context Internally But It Doesn’t Expose This Fact In The Public API. So You
Should Feel Much Safer Using Context Via React Redux Than Directly Because If It Changes, The
Burden Of Updating The Code Will Be On React Redux Instead Developer Responsibility.
- If You Change The Reducer Code, Each “Staged” Action Will Be Re-Evaluated
- If The Reducers Throw, You Will See During Which Action This Happened, And What The Error Was
With PersistState() Store Enhancer, You Can Persist Debug Sessions Across Page Reloads
- These Libraries Are Very Different For Very Different Purposes, But There Are Some Vague
Similarities.
- Redux Is A Tool For Managing State Throughout The Application. It Is Usually Used As An
Architecture For UIs. Think Of It As An Alternative To (Half Of) Angular.
Redux Uses The Reactive Paradigm Little Bit Because The Store Is Reactive. The Store Observes
Actions From A Distance, And Changes Itself. RxJS Also Uses The Reactive Paradigm, But Instead Of
Being An Architecture, It Gives You Basic Building Blocks, Observables, To Accomplish This
"Observing From A Distance" Pattern.
- Code-Splitting Is A Feature Supported By Bundlers Like Webpack, Rollup And Browserify (Via
Factor-Bundle) Which Can Create Multiple Bundles That Can Be Dynamically Loaded At Runtime.
- Most React Apps Will Have Their Files “Bundled” Using Tools Like Webpack, Rollup Or Browserify.
Bundling Is The Process Of Following Imported Files And Merging Them Into A Single File: A
“Bundle”. This Bundle Can Then Be Included On A Webpage To Load An Entire App At Once
Q.What Is React.Lazy
- React.Lazy Is The Recommended Solution For Code Splitting. It Uses Suspense And It Is Maintained
By React.
React.Lazy-
- Support Suspense
- Not Supporting SSR
@Loadable/Component-
- Support Suspense
- Supporting SSR
- Supporting Import(`./${Value}`)
- React Suspense Is A Generic Way For Components To Suspend Rendering While They Load Data
From A Cache. It Is A Fundamentally New Capability That: Lets You Render A Component Tree “In
Background” While Components Are Fetching Data, And. Display Them Only After The Whole Tree Is
Ready
- Such Functions Are Called “Pure” Because They Do Not Attempt To Change Their Inputs, And
Always Return The Same Result For The Same Inputs. React Is Pretty Flexible But It Has A Single Strict
Rule: All React Components Must Act Like Pure Functions With Respect To Their Props.
- Components Are The Building Blocks Of Any React Application, And A Single App Usually Consists
Of Multiple Components. A Component Is Essentially A Piece Of The User Interface. It Splits The User
Interface Into Independent, Reusable Parts That Can Be Processed Separate
- Statelfull Components
- Stateless Components
- These Types Of Components Have No State Of Their Own And Only Contain Render Methods, And
Therefore Are Also Called Stateless Components. They May Derive Data From Other Components As
Props (Properties).
- These Types Of Components Can Hold And Manage Their Own State And Have A Separate Render
Method To Return JSX On The Screen. They Are Also Called Stateful Components As They Can Have A
State.
- Flux Is The Application Architecture That Facebook Uses For Building Web Applications. It Is A
Method Of Handling Complex Data Inside A Client-Side Application And Manages How Data Flows In
A React Application.
- There Is A Single Source Of Data (The Store) And Triggering Certain Actions Is The Only Way Way To
Update Them.The Actions Call The Dispatcher, And Then The Store Is Triggered And Updated With
Their Own Data Accordingly
- When A Dispatch Has Been Triggered, And The Store Updates, It Will Emit A Change Event That The
Views Can Rerender Accordingly.
Redux-
Flux
- Require Vs. Import – The Require Used In ES5 Is Now Replaced With Import. Var React =
Require('React'); //Is Now Replaced With Import React From 'React'; //In ES6
- Export Vs. Exports – Instead Of Exports, Now Export Is Used.Export Default Component; // Replaces
Module.Exports = Component; // In ES6
- Component And Function – The Use Of Component And Function Has Also Changed From ES5 To
ES6.
Q. You Must’ve Heard That “In React, Everything Is A Component.” What Do You Understand From
The Statement?
- The Building Blocks Of A React Application’s UI Are Called Components. Any App UI Created Using
React Is Divisible Into A Number Of Small Independent And Reusable Pieces, Known As Components.
React Renders Each Of The Components Independent Of Each Other. Hence, There Is No Effect Of
Rendering A Component On The Rest Of The App UI.
- The Parent Component Can Change The Value In Props But Not In The State.
- The Changes Can Be Made Inside The State But Not In Props.
- The Synthetic Events In React Are The Objects In React, Which Acts As A Cross-Browser Wrapper
Around The Browser's Native Event. The Main Purpose Is To Combine The Different Browsers On The
API So That The Event Shows Various Properties.
- Yes, We Can Modularize Code In React. It Can Be Done By Using Export And Import Properties.
- We Can Use Context In Our Application Directly And Is Going To Be Great For Passing Down Data To
Acutely Nested Components That What It Was Designed For. Whereas Redux Is Much More Potent
And Provides A Large Number Of Skin Textures That The Context API Doesn’t Provide. Also, React
Redux Uses Context Internally But It Doesn’t Render This Fact In The Public API.
- React -JavaScript Library, Supporting Both Front-End Web And Being Run On The Server, For
Building User Interfaces And Web Applications. React Native – Mobile Framework That Compiles To
Native App Components, Allowing You To Build Native Mobile Applications (IOS, Android, And
Windows) In JavaScript That Allows You To Use React To Build Your Components, And Implements
React Under The Hood.
- Element – A Plain Object Describing What We Want To Appear On The Screen In Terms Of The
DOM Nodes / Other Components. Elements Can Contain Other Elements In Their Props. Creating A
React Element Is Cheap. Once An Element Is Created, It Is Never Mutated.
- Component – Declared In Several Ways. Component Can Class With A Render() Method.
Alternatively It Can Be Defined As A Function. Component Takes Props As An Input, And Returns An
JSX Tree As The
- The Super Keyword Is Used To Access & Call Functions On An Object’s Parent.
- A Callback Function Should Be Called When SetState Has Finished, And The Component Is Re-
Rendered. As The SetState Is Asynchronous, Which Is Why It Takes In A Second Callback Function.
- Keys Allow You To Provide Each List Element With A Stable Identity. The Keys Should Be Unique.
- Error Boundaries Help You To Catch Javascript Error Anywhere In The Child Components. They Are
Most Used To Log The Error And Show A Fallback UI.
- Webpack In Basically Is A Module Builder. It Is Mainly Runs During The Development Proc
- Babel, Is A JavaScript Compiler That Converts Latest JavaScript Like ES6, ES7 Into Plain Old ES5
JavaScript That Most Browsers Understand.
- When A Component’s State Or Props Change Then Rest Will Compare The Rendered Element With
Previously Rendered DOM And Will Update The Actual DOM If It Is Needed. This Process Is Known As
Reconciliation.
- The Process Of Detaching The Element From The DCOM Is Called The Demounting Process
- Most Important Protoype Used In React Js Are: Number, String, Array, Object, Element
- BrowserRouter Is The Router Implementation For HTML5 Browsers (Vs Native): - Link Is Your
Replacement For Anchor Tags.
- Switch Returns Only The First Matching Route Rather Than All Matching Routes.
- The Component Will Only Render The First Route That Matches/Includes The Path. Once It Finds
The First Route That Matches The Path, It Will Not Look For Any Other Matches. Not Only That, It
Allows For Nested Routes To Work Properly, Which Is Something That Will Not Be Able To Handle
- The Term “History” And " History Object" In This Documentation Refers To The History Package,
Which Is One Of Only 2 Major Dependencies Of React Router (Besides React Itself), And Which
Provides Several Different Implementations For Managing Session History In JavaScript In Various
Environments
- SetState() Does Not Immediately Mutate This.State But Creates A Pending State Transition.
Accessing This.State After Calling This Method Can Potentially Return The Existing Value. There Is No
Guarantee Of Synchronous Operation Of Calls To SetState And Calls May Be Batched For
Performance Gains.
- This Is Because SetState Alters The State And Causes Rerendering. This Can Be An Expensive
Operation And Making It Synchronous Might Leave The Browser Unresponsive. Thus The SetState
Calls Are Asynchronous As Well As Batched For Better UI Experience And Performance
- A Component Can Specify The Layout Of Its Children Using The Flexbox Algorithm. Flexbox Is
Designed To Provide A Consistent Layout On Different Screen Sizes.
- The Effect Hook, UseEffect, Adds The Ability To Perform Side Effects From A Function Component.
It Serves The Same Purpose As ComponentDidMount, ComponentDidUpdate, And
ComponentWillUnmount In React Classes, But Unified Into A Single API.