React Component Lifecycle Methods from v16.3 with example
react
23
lifecycle
2
Male avatar

loveprogramming viết ngày 31/03/2021

React Component Lifecycle Methods from v16.3 with example

https://grokonez.com/frontend/react/react-component-lifecycle-methods-from-v16-3-react-lifecycle-example

From v16.3, React introduces new 2 lifecycles getDerivedStateFromProps, getSnapshotBeforeUpdate, and also notices that 3 methods will be in time considered deprecation componentWillMount, componentWillUpdate, componentWillReceiveProps. In this tutorial, we're gonna look at new React Component Lifecycle Methods, then we will build an example that uses them.

Component Lifecycle

react-component-lifecycle-methods-diagram

Mounting methods

constructor()

This method will be called whenever a new object is created. super(props) calls the constructor of parent class (React.Component) to initialize itself. Now we have access to this.props.

constructor() is used for setting up Component such as creating class fields or initialize state by directly overwriting the this.state. Don’t call this.setState() here.

It is also often used to bind functions that will be passed as callbacks.


constructor(props) {
    super(props);
    this.add = this.add.bind(this);
    this.minus = this.minus.bind(this);

    this.state = {
        counter: 0,
        anotherCounter: props.initialCounter        
    }
}

Don't make any side effects (AJAX call for example) or subscription in the constructor. Use componentDidMount() instead.

static getDerivedStateFromProps()

This method is invoked after a Component is instantiated as well as when it receives new props.

Static method doesn't exist on instance, but the class. So it does not have access to this keyword. It helps us NOT call this.setState() here, instead we should return an object to update state, or null if no update is needed (only need to return the part of state that changes, other will be preserved).

*Note:

  • If parent Component causes this Component to re-render, this method will be called even if props have not changed => compare new and previous values if we want to handle changes.

  • Calling this.setState() doesn’t trigger getDerivedStateFromProps().

    
    static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.counter > nextProps.maxCount) {
        console.log('set counter to [' + nextProps.maxCount + ']');
        return {
            counter: nextProps.maxCount
        };
    }
    
    console.log('check MAX counter >> no need to change counter!');
    return null;
    }
    

    render()

    This method is required.

When render() is called, it analyses this.props and this.state and return React elements (native DOM Component or a user-defined composite Component), String or number, Portal, null or Boolean (render nothing).

render() should not modify component state or directly interact with the browser. If you need to interact with the browser, use componentDidMount() or the other lifecycle methods instead.

*Note:: render() will not be invoked if shouldComponentUpdate() returns false.

render() {
    return (
        <div>
            <h1>Java Sample Approach</h1>
            <h3>{this.props.maxCount}</h3>
            <p>Counter: {this.state.counter}</p>
            <button onClick={this.add}>ADD+</button>
            <CalculatorComponent />
        </div>
    );
}

React Component Lifecycle Methods from v16.3 with example

https://grokonez.com/frontend/react/react-component-lifecycle-methods-from-v16-3-react-lifecycle-example

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

Male avatar

loveprogramming

444 bài viết.
77 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 6 tháng trước
1 0
Male avatar
1 0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 5 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 5 tháng trước
1 0
Bài viết liên quan
Male avatar
4 0
Autolayout và lifecycle trong IOS 1. Lý thuyết: Trước hết, mình xin nói về một vài lifecycle trong swift để mọi người nhớ lại. Một câu hỏi phổ b...
Bùi Khánh Duy viết 3 năm trước
4 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
444 bài viết.
77 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!