Stateful components and life cycle methods

React components can manage their own state and update only when the state has changed. Stateful React components are written using ES6 classes:

class Example extends React.Component { 
   render() { 
      <span>This is an example</span> 
   } 
} 

React class components have a state instance property to access their internal state and a props property to access properties passed to the component:

class Example extends React.Component {  
    state = { title: null } 
    render() { 
        return ( 
            <React.Fragment>  
                <span>{this.props.title}</span>  
                <span>{this.state.title}</span>  
            </React.Fragment>  
        ) 
    } 
} 

And their state can be mutated by using the setState instance method:

class Example extends React.Component { 
    state = { 
        title: "Example", 
        date: null, 
    } 
    componentDidMount() { 
        this.setState((prevState) => ({ 
            date: new Date().toDateString(), 
        })) 
    } 
    render() { 
        return ( 
            <React.Fragment>  
                <span>{this.state.title}</span>  
                <span>{this.state.date}</span>  
            </React.Fragment>  
        ) 
    } 
} 

The state is initialized once. Then, when the component is mounted, the state should only be mutated using the setState method. This way, React is able to detect changes in the state and update the component.

The setState method accepts a callback function as the first argument which will be executed passing the current state (prevState for convention) as the first argument to the callback function and the current props as the second argument. This is so because setState works asynchronously and the state could be mutated while you are performing other actions in different parts of your component.

If you don't need access to the current state while updating the state, you can directly pass an object as the first argument. For instance, the previous example could have been written as:

componentDidMount() { 
   this.setState({ 
      date: new Date().toDateString(), 
   }) 
} 

setState also accepts an optional callback function as a second argument that gets called once the state has been updated. Because setState is asynchronous, you may want to use the second callback to perform an action only once the state has been updated:

componentDidMount() { 
   this.setState({ 
      date: new Date().toDateString(), 
   }, () => { 
      console.log('date has been updated!') 
   }) 
   console.log(this.state.date) // null 
} 

Once the component is mounted, the console will first output null even though we used setState before it; that's because the state is set asynchronously. However, once the state is updated, the console will display "date has been updated".

When using the setState method, React merges the previous state with the current given state. Internally, it's similar to doing:
currentState = Object.assign({}, currentState, nextState) 

Every class component has life cycle methods that give you control over the life of your component since its creation until it's destroyed, as well as giving you control over other properties, such as knowing when the component has received new properties and if the component should be updated or not. These are the life cycle methods present in all class components:

  • constructor(props): This is invoked when initializing a new instance of the component, before the component is mounted. props must be passed to the super class using super(props) to let React set the props correctly. The constructor method is useful as well to initialize the initial state of the component.
  • static getDerivedStateFromProps(nextProps, nextState): This is invoked when the component has been instantiated and when the component will receive new props. This method is useful when the state or part of it depends on values received from the props passed to the component. It must return an object which will be merged with the current state or null if the state doesn't need to be updated after receiving new props.
  • componentDidMount(): This is invoked after the component has been mounted and after the first render call. It's useful for integrating with third-party libraries, accessing the DOM, or making HTTP requests to an endpoint.
  • shouldComponentUpdate(nextProps, nextState): This is invoked when the component has updated the state or new props have been received. This method allows React to know if it should update the component or not. If you don't implement this method in your component, it defaults to returning true, which means the component should be updated every time the state has changed or new props have been received. If implementing this method and returning false, it will tell React not to update the component.
  • componentDidUpdate(prevProps, prevState, snapshot): This is invoked after the render method or when an update occurs, except for the first rendering.
  • getSnapshotBeforeUpdate(prevProps, prevState): This is invoked after the render method or when an update occurs but before the componentDidUpdate life cycle method. The returned value of this method is passed as the third argument of componentDidUpdate.
  • componentWillUnmount(): This is invoked before a component is unmounted and its instance destroyed. If using third-party libraries, this method is helpful for cleaning up. For instance, clearing timers or cancelling network requests.
  • componentDidCatch(error, info) : This is a new feature of React v16 for error handling. We will look at this in more detail in the following recipes.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.145.173