Thursday, July 9, 2020

React Components Lifecycle

React Components Lifecycle React Components Props and States in ReactJS with Examples Back Home Categories Online Courses Mock Interviews Webinars NEW Community Write for Us Categories Artificial Intelligence AI vs Machine Learning vs Deep LearningMachine Learning AlgorithmsArtificial Intelligence TutorialWhat is Deep LearningDeep Learning TutorialInstall TensorFlowDeep Learning with PythonBackpropagationTensorFlow TutorialConvolutional Neural Network TutorialVIEW ALL BI and Visualization What is TableauTableau TutorialTableau Interview QuestionsWhat is InformaticaInformatica Interview QuestionsPower BI TutorialPower BI Interview QuestionsOLTP vs OLAPQlikView TutorialAdvanced Excel Formulas TutorialVIEW ALL Big Data What is HadoopHadoop ArchitectureHadoop TutorialHadoop Interview QuestionsHadoop EcosystemData Science vs Big Data vs Data AnalyticsWhat is Big DataMapReduce TutorialPig TutorialSpark TutorialSpark Interview QuestionsBig Data TutorialHive TutorialVIEW ALL Blockchain Blockchain TutorialWhat is BlockchainHyperledger FabricWhat Is EthereumEthereum TutorialB lockchain ApplicationsSolidity TutorialBlockchain ProgrammingHow Blockchain WorksVIEW ALL Cloud Computing What is AWSAWS TutorialAWS CertificationAzure Interview QuestionsAzure TutorialWhat Is Cloud ComputingWhat Is SalesforceIoT TutorialSalesforce TutorialSalesforce Interview QuestionsVIEW ALL Cyber Security Cloud SecurityWhat is CryptographyNmap TutorialSQL Injection AttacksHow To Install Kali LinuxHow to become an Ethical Hacker?Footprinting in Ethical HackingNetwork Scanning for Ethical HackingARP SpoofingApplication SecurityVIEW ALL Data Science Python Pandas TutorialWhat is Machine LearningMachine Learning TutorialMachine Learning ProjectsMachine Learning Interview QuestionsWhat Is Data ScienceSAS TutorialR TutorialData Science ProjectsHow to become a data scientistData Science Interview QuestionsData Scientist SalaryVIEW ALL Data Warehousing and ETL What is Data WarehouseDimension Table in Data WarehousingData Warehousing Interview QuestionsData warehouse architectureTalend T utorialTalend ETL ToolTalend Interview QuestionsFact Table and its TypesInformatica TransformationsInformatica TutorialVIEW ALL Databases What is MySQLMySQL Data TypesSQL JoinsSQL Data TypesWhat is MongoDBMongoDB Interview QuestionsMySQL TutorialSQL Interview QuestionsSQL CommandsMySQL Interview QuestionsVIEW ALL DevOps What is DevOpsDevOps vs AgileDevOps ToolsDevOps TutorialHow To Become A DevOps EngineerDevOps Interview QuestionsWhat Is DockerDocker TutorialDocker Interview QuestionsWhat Is ChefWhat Is KubernetesKubernetes TutorialVIEW ALL Front End Web Development What is JavaScript â€" All You Need To Know About JavaScriptJavaScript TutorialJavaScript Interview QuestionsJavaScript FrameworksAngular TutorialAngular Interview QuestionsWhat is REST API?React TutorialReact vs AngularjQuery TutorialNode TutorialReact Interview QuestionsVIEW ALL Mobile Development Android TutorialAndroid Interview QuestionsAndroid ArchitectureAndroid SQLite DatabaseProgramming Props... ReactJS (7 Bl ogs) Become a Certified Professional AWS Global Infrastructure Introduction to ReactJS What Is React? â€" Unveil The Magic Of Interactive UI With ReactReact vs Angular â€" Battle Between The JavaScript Heavy WeightsReactJS vs AngularJS: What are the Comparison Factors?Flutter vs React Native â€" Which One You Should Learn? React Basics ReactJS Tutorial â€" Design Your Web UI Using ReactJS JavaScript LibraryReact Components â€" Props and States in ReactJS with Examples React Libraries React Redux Tutorial â€" Efficient Management of States in ReactReact Router v4 Tutorial â€" Create Routing for your React Apps React Interview Questions Top 50 React Interview Questions You Must Prepare In 2020Front End Web Development Topics CoveredAngularJS (34 Blogs)jQuery UI Development (2 Blogs)The Complete WebDeveloper (39 Blogs)ReactJS (7 Blogs)SEE MORE React Components Props and States in ReactJS with Examples Last updated on May 22,2019 17.2K Views Swatee Chand Research Analyst at Edureka. A techno freak who likes to explore different... Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write about... Bookmark 2 / 2 Blog from React Basics Become a Certified Professional In React, everything is a componentIf you are familiar with React, then you must have heard or read this phrase many times. But do you know what it means exactly and how it is used? If you dont, then read this blog to learn all about React components and the different phases in the lifecycle. I am sure by the time you finishreading this blog you will have a complete understanding about React components and the concepts surrounding it. But before proceeding, take a quick look at the topics I will be discussing:What are React Components?Advantages of React ComponentsPropsStatesStates vs PropsReact Component LifecycleWhat are React Components?Earlier the developers had to write 1000 lines of code for developing a simple single page application. Most of those applications followed the traditional DOM structure and making changes to them was very challenging and a tedious task for the developers.They manually had to search for the element which needed the change and update it accordingly. Even a small mistake would lead to application failure. Moreover, updating DOM was very expensive. Thus, the component-based approach was introduced. In this approach, the entire application is divided into logical chunks which are called the Components.React was one of the frameworks who opted for this approach.If you are planning to build your career in web development, early start would open lots of opportunities for you. Get Certified Get Ahead.Lets now understand what these components are.React components are considered as the building blocks of the User Interface. Each of these components exists within the same space but execute independently from one another. React components have their ow n structure, methods as well as APIs. They are reusable and can be injected into interfaces as per need. To have a better understanding, consider the entire UI as a tree.Here the starting component becomes the root and each of the independent pieces becomes branches, which are further divided into sub-branches.This keeps our UI organized and allows the data and state changes to logically flow from the root to branches and then to sub-branches.Components make calls to the server directly from the client-side which allows the DOM to update dynamically without refreshing the page. This is because react components are built on the concept of AJAX requests. Each component has its own interface that can make calls to the server and update them. As these components are independent of one another, each can refresh without affecting others or the UI as a whole.We use React.createClass()method to create a component. This method must be passed an object argument which will define the React com ponent. Each component must contain exactly one render() method. It is the most important property of a component which isresponsible for parsing the HTML in JavaScript,JSX. This render() will return the HTML representation of the component as a DOM node. Therefore, all the HTML tags must be enclosed in an enclosing tag inside the render().Following is a sample code for creating a component. import React from 'react'; import ReactDOM from 'react-dom'; class MyComponent extends React.Component{ render(){ return( div h1Hello/h1 h1This is a Component/h1 /div ); } } ReactDOM.render( MyComponent/, document.getElementById('content') ); Advantages of React ComponentsCode Re-usability Acomponent-based approach makes your application development easier and faster. If you want to use a pre-existing functionality in your code, you can just put that code in yours instead of building it from scratch.It also allows your application architecture to stay up to date over time as you can update the specific areas which need up-gradations.Fast Development A component-based UI approach leads to an iterative and agile application development. These components are hosted in a library from which different software development teams can access, integrate and modify them throughout the development process.Consistency Implementing these reusable components helps to keep the design consistent and can provide clarity in organizing code throughout the application.Maintainability Applications with a set of well-organized components can be quickly updated and you can be confident about the areas which will be affected and which wont.Scal ability The development becomes easier with a properly organized library of ready to implement components. Ensuring the components are properly namespaced helps to avoid style and functionality leaking or overlapping into the wrong place as the project scales up.Easy Integration The componentcodes are stored in repositories like GitHub, which is open for public use. Application development teams are well-versed in using source code repositories, and so they are able to extract the code as needed and inject it into the application.Now that you have understood what is a component and what are its advantages, lets now find out how to feed data to these components.There are two ways the components receive data:PropsStatesPropsProps standfor Properties. They are the read-only components which work similar to the HTML attributes. Prop is a way of passing data from parent to child component. Lets understand this with an example.As we already know, the react components arrange the UI in t he form of a tree where the parent component becomes the root and child components become branches and sub-branches. Now suppose parent component wants to send data to one of its deeply nested components. Let us say from component 1 you need to send a property to component 6. How will you do that?You cannot pass down a property directly to the target component. This is becauseReact follows the rule where properties have to flow down from a parent component to an immediate child component.This means you cant skip a layer of child components when sending a property and the child components cant send property back up to a parent as well. You can have default props in casea parent component doesnt pass down props so that they are still set. This is why React has one-way data binding. So, in this case, we need to send data, layer by layer until it reaches target child component.Every component in this path has to receive the property from its parent and then resend that property to its c hild as received. This process repeats until your property reaches its target component.Here is an example of passing the props. import React from 'react'; import ReactDOM from 'react-dom'; class MyComponent extends React.Component{ render(){ return( div h1Hello/h1 Header name=maxx id=101/ /div ); } } function Header(props) { return ( div Footer name = {props.name} id = {props.id}/ /div ); } function Footer(props) { return ( div h1 Welcome : {props.name}/h1 h1 Id is : {props.id}/h1 /div ); } ReactDOM.render( MyComponent/, document.getElementById('content') ); Since the props can only be passed from parent components, they cannot be changed. This makes them immutable and dumb. This poses a great challenge as the modern apps do not have all of its states ready on page load. Ajax or Events can happen when data returns, so someone needs to take responsibility for handling the updates. This is where React states come into the picture.StatesGenerally, components take in props and render them. These are called stateless components. But they can also provide state which are used to store data or information about the component which can change over time. Such components are called stateful components. The change in state can happen as a response to user event or system event. In other words, state is the heart of every react component which determines how the component will behave and render. They are also responsible for making a component dynamic and interactive. Thus they must be kept as simple as possible.The state can be accessed with this r eference, e.g., this.state. You can access and print variables in JSX using curly braces {}. Similarly, you can render this.state inside render().You must set a default state for the component else it will set to null.Now lets see how a state is assigned to a component. import React from 'react'; import ReactDOM from 'react-dom'; class MyComponent extends React.Component { constructor() { super(); this.state = { name: 'Maxx', id: '101' } } render() { setTimeout(()=;{this.setState({name:'Jaeha', id:'222'})},2000) return ( div h1Hello {this.state.name}/h1 h2Your Id is {this.state.id}/h2 /div ); } } ReactDOM.render( MyComponent/, document.getElementById('content') ); States vs PropsReact Component LifecycleReact provides various methods which notify when a certain stage in the lifecycle of a component occurs. These methods are called the lifecycle methods.These lifecycle methods are not very complicated. You can think of these methods as specialized event handlers that are called at various points during a components life. You can even add your own code to these methods to perform various tasks. Talking about the lifecycle of the component, the lifecycle is divided into 4 phases. They are:Initial PhaseUpdating PhaseProps change PhaseUnmounting PhaseEach of these phases contains some lifecycle methods which are specific only to them. So lets now find out what happens during each of these phases.a. Initial Phase The first phase of the lifecycle of a React component is the initial phase or initial rendering phase. In this phase, the component is about to start its journey and make its way to the DOM. This phase consists of the following methods whi ch are invoked in a predefined order.getDefaultProps(): This method is used to specify the default value of this.props. It gets called before your component is even created or any props from the parent are passed into it.getInitialState(): This method is used tospecifythe default value of this.state before your component is created.componentWillMount():This is the last method that you can call before your component gets rendered into the DOM. But if you call setState() inside this method your component will not re-render.render(): This method is responsible for returning a single root HTML node and must be defined in each and every component. You can return null or false in case you dont want to render anything.componentDidMount(): Once the component is rendered and placed on the DOM, thismethod is called. Here you can perform any DOM querying operations.b. Updating Phase Once the component is added to the DOM, they can update and re-render only when a state change occurs. Each tim e the state changes, the component calls its render() again. Any component, that relies on the output of this component will alsocall its render() again. This is done, to ensure that our component is displaying the latest version of itself. Thus to successfully update the components state the following methods are invoked in the given order:shouldComponentUpdate():Using this method you can control your components behavior of updating itself. If you return a true from this method,the component will update. Else if this method returns a false, the component will skip the updating.componentWillUpdate(): This method is calledjust before your component is about to update. In this method, you cant change your component state by calling this.setState.render():If you are returning false viashouldComponentUpdate(), the code inside render() will be invoked again to ensure that your component displays itself properly.componentDidUpdate():Once the component is updated and rendered, then this me thod is invoked. You can put any code inside this method, which you want to execute once the component is updated.c. Props Change Phase Afterthe component has been rendered into the DOM, the only other time the component will update, apart from the state change is when its prop value changes. Practically this phase works similar to the previous phase, but instead of the state, it deals with the props. Thus, this phase has only one additional method from the Updating Phase.componentWillReceiveProps():This method returns one argument which contains the new prop value that is about to be assigned to the component. Rest of the lifecycle methods behave identically to the methods which we saw in the previous phase. shouldComponentUpdate()componentWillUpdate()render()componentDidUpdate()d.The Unmounting Phase This is the last phase of components life cycle in which the component is destroyed and removed from the DOM completely. It contains only one method:componentWillUnmount(): Once thi s method is invoked, your component is removed from the DOM permanently.In this method,you can perform any clean-up related tasks like removing event listeners, stopping timers, etc.Following is the entire life cycle diagram:This brings us to the end of the blog on React Components. I hope in this blog I was able to clearly explain what are React Components, how they are used. You can refer to my blog onReactJS Tutorial, in case you want to learn more about ReactJS.If you want to get trained in React and wish to develop interesting UIs on your own,then check out theReactJS with Redux Certification Trainingby Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.Got a question for us? Please mention it in the comments section and we will get back to you.Recommended videos for you Web Development Trends and Predictions Watch Now Angular 4 Tutorial Getting Started With Angular 4 Watch Now Trendy Web Designs using HTML 5 Watch Now AngularJS : Superheroic JavaScript MVW Framework Watch Now Whats New in Angular 4 Angular 4 Features Watch Now AngularJS-Superheroic JavaScript MVW Framework Watch Now Deep Dive into AngularJS Javascript Framework Watch Now Are You Riding The AngularJS Wave Yet? Watch Now Animation And Testing In AngularJS Watch Now Web Development with HTML5, CSS3 JavaScript Watch Now Angular JS : Develop Responsive Single Page Application Watch Now AngularJS Develop Responsive Single Page Application Watch Now A Work Day Of A Web Developer Watch Now Angular JS Tutorial for Beginners Watch NowRecommended blogs for you ReactJS Tutorial Design Your Web UI Using ReactJS JavaScript Library Read Article Important JavaScript Functions You Need to Know About Read Article React vs Angular Battle Between The JavaScript Heavy Weights Read Article How To Best Utilize Nested Tables In HTML? Read Article How to Implement Form Validation in Angular JS? Read Article What are HTML Meta Tags? Is it Really Necessary? Read Article Array Methods In JavaScript: Everything You Need To Know About Array methods Read Article How to Implement Splice method() in Javascript? Read Article Split in PHP: What is str_split() function Read Article How to Perform Email Validation in JavaScript? Read Article Angular Directive: Learn How To Work With Directives In Angular Read Article How to Implement Pagination in Angular JS Read Article What is CSS? The Style Statement of the Internet Read Article Angular Routing: A Complete Guide for Beginners Read Article jQuery Tutorial A Complete Guide For Beginners Read Article ReactJS vs AngularJS: What are the Comparison Factors? Read Article How To Implement Promises in JavaScript? Read Article What are Events in JavaScript and how they are handled? Read Article What is the difference Between CSS and CSS3? Read Article How to Implement JavaScript Date Methods? Read Article Comments 0 Comments Trending Courses in Front End Web Development Angular Certification Training15k Enrolled LearnersWeekendLive Class Reviews 5 (5700)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.