Skip to content

65. Is it good to use setState() in componentWillMount() method? #78

@AnandKumarJha

Description

@AnandKumarJha

The answer written here is wrong. I think it is taken from this stack overflow link https://stackoverflow.com/questions/40199151/cant-set-state-in-componentwillmount. There reason behind setState not working was some parsing error. I think the answer for it need to be updated. I have tested it with the below code and it working properly with componentWillMount.

import React, { Component } from 'react';
import { Text } from 'react-native';

class Cat extends Component {

constructor(props) {
super(props)
this.state = {
name: 'Anand'
};
}

componentWillMount() {
setTimeout(()=> {
this.setState({name:'anand Kumar jha will'})
}, 3000)
}

componentDidMount() {
setTimeout(()=> {
this.setState({name:'anand Kumar jha did'})
}, 1000)
}

render() {
return (
Hello, I am your cat! {this.state.name}
);
}
}

export default Cat;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions