Patrick
Patrick

Reputation: 876

React, Should I set state from props?

I always use props directly without set it to state and it works just fine, but should I really set state from props and then use that state instead. what's the difference?

Class A extends Component {
    ...some method,
    render() {
      return <>{this.props.message}</>
    }
}

Class A extends Component {
    constructor() {
       super();
       this.state = {
          message: ''
       }
    }
    componentDidMount(){
       this.setState({message: this.props.message})
    }
    render() {
      return <>{this.state.message}</>
    }
}

Upvotes: 1

Views: 3804

Answers (2)

S M Hammad Shakil
S M Hammad Shakil

Reputation: 99

It is better to use data from props no need to update it to state it just add some 2 3 lines of code and additional execution of setState function but user will not feel any difference at all.

Upvotes: 0

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

There really is no need if the values are identical. Consider that every time you use this.setState() you cause an additional re-render of your component. A small price to pay, but something that can mean much more later on if you have let's say 10000 messages. So it wouldn't provide any benefit by updating state. Just use props directly.

It would make some sense to update state if you plan on using the props as an intermediary check. Let's say you have something like this:

class App extends React.Component{
   state = {
     display: none
   }

   componentDidUpdate(){
      if(this.props.data.length > 0){
        this.setState({
           display: true
        })
      }
   }

   render(){
     <div>
       { this.state.display ? "Show value" : "" }
     </div>
   }
}

We can use props to update a state-value that determines if we should display some content.

Upvotes: 2

Related Questions