Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Getting Started with React Router

DZone's Guide to

Getting Started with React Router

Components make the React world go 'round. Read on to get a great overview of the most useful components, and how to apply them to your app.

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

All React components go through a lifecycle which enables you to perform a specific task at any specific time. In order to achieve that, you can override the lifecycle methods. Methods prefixed with will are called right before something occurs (events), and methods prefixed with did are called right after something occurs.

Let us understand all the functions in all the phases of the lifecycle:

setup props and state(constructor(props))

Constructors are a basic building block of OOP. It is the first function which will be called whenever a new object is created, even if it is called before the component is mounted. One thing that should be noted is that before any lines of a statement, you should call super(props) in order to use this.props. It will call the constructor of the parent in order to make "props" available to our constructor.

This is also the only place where you are expected to change/set the state by directly overwriting the this.state fields. In all other instances, remember to use this.setState.

componentWillMount(componentWillMount())

This is deprecated. It is not that much different from the constructor. It is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger extra rendering. But it is recommended to use a constructor for the same purpose.

render(render())

Among all the React functions,render() is the most famous. We create elements (generally via JSX) and return them. We access the component via this.props and this.state and these values tell us about how content should be generated. Any changes we made during componentWillMount() are fully applied to this.state.

render() must not allow the modification of the component state. It returns the same result each time it’s invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in other lifecycle methods.

componentDidMount(componentDidMount())

componentDidMount() is invoked just after the mounting of a component. Statements that require the DOM, i.e. which need the UI to be rendered, should be kept here. Don't use setState() in this method, as it will trigger extra rendering. Though the user will not see the extra rendering, it will cause performance issues.

componentWillReceiveProps(componentWillReceiveProps(nextProps))

This is deprecated. componentWillReceiveProps() is invoked before a component receives new props. In this method, you can compare the previous props with the newer one and, based on what you find, you can change the state and make other updates accordingly.

Calling this.setState()doesn’t trigger componentWillReceiveProps().

shouldComponentUpdate(shouldComponentUpdate(nextProps, nextState))

This can be used to let React know if a component’s output is affected by the current change in state or props. Talking about the default behavior of this function, it will re-render on every state change.

This method is not called for the initial render. If this method returns false, then componentWillUpdate()render(), and componentDidUpdate() will not be invoked.

It is not recommended to do deep checks or use JSON.stringify() in shouldComponentUpdate(). It will badly degrade the performance.

componentWillUpdate(componentWillUpdate(nextProps, nextState))

This method is invoked just before rendering when new props or states are being received. This method is not called for the initial render. You can do the stuff required before the update occurs.

This method is only invoked if shouldComponentUpdate() is invoked.

componentDidUpdate(componentDidUpdate(prevProps, prevState, snapshot))

This method is invoked just after an update occurs. This method is not called for the initial render. Statements that requires the DOM, i.e. those that are needed after the UI is updated, should be kept here. It is the place where you can perform server calls after comparing current and previous props.

componentWillUnmount(componentWillUnmount())

This is the method which is invoked immediately before a component is unmounted and destroyed. You can write the statements to clean up any resource. 

We can understand it with the help of an example. Here we are setting the initial state inside of the constructor. The setDigit is used to update the state.

App.js

import React from 'react';
import Content from './Content';
class App extends React.Component {
   constructor(props) {
      super(props);

      this.state = {
         myDigit: 0
      }
      this.setDigit = this.setNewNumber.bind(this)
   };
   setNewNumber() {
      this.setState({myDigit: this.state.myDigit + 1})
   }
   render() {
      return (
         <div>
            <button onClick = {this.setDigit}>INCREMENT</button>
            <Content sentDigit = {this.state.data}></Content>
         </div>
      );
   }
}
export default App;

Content.js

import React from 'react'
class Content extends React.Component {
   componentWillMount() {
      console.log('Component WILL MOUNT!')
   }
   componentDidMount() {
      console.log('Component DID MOUNT!')
   }
   componentWillReceiveProps(newProps) {    
      console.log('Component WILL RECIEVE PROPS!')
   }
   shouldComponentUpdate(newProps, newState) {
      return true;
   }
   componentWillUpdate(nextProps, nextState) {
      console.log('Component WILL UPDATE!');
   }
   componentDidUpdate(prevProps, prevState) {
      console.log('Component DID UPDATE!')
   }
   componentWillUnmount() {
      console.log('Component WILL UNMOUNT!')
   }
   render() {
      return (
         <div>
            <h1>{this.props.sentDigit}</h1>
         </div>
      );
   }
}
export default Content

Main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

setTimeout(() => {
   ReactDOM.unmountComponentAtNode(document.getElementById('app'));}, 5000);

After the initial rendering, the screen will show:

And the console will contain the following:

Component WILL MOUNT!
Component DID MOUNT!

After clicking the INCREMENT button, the update will call other lifecycle methods.

Component WILL RECEIVE PROPS!
Component WILL UPDATE!
Component DID UPDATE!

And after 5 seconds, the component will unmount and the log will show:

Component WILL UNMOUNT!

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:
web dev ,react.js ,react components ,react.js development ,front-end development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}