1

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}</>
    }
}
Patrick
  • 734
  • 11
  • 26
  • 1
    only use state if you need to update data live in the UI. something like an input controller for instance. there are other use cases for state besides this (update a class name, loading flags... etc), but in general its when you need to have a component do something other than just render data – John Ruddell Jul 19 '19 at 07:22
  • 2
    Possible duplicate of [What is the difference between state and props in React?](https://stackoverflow.com/questions/27991366/what-is-the-difference-between-state-and-props-in-react) – John Ruddell Jul 19 '19 at 07:25

2 Answers2

2

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.

Chris Ngo
  • 15,460
  • 3
  • 23
  • 46
0

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.