Jose Alves
Jose Alves

Reputation: 142

How can I get started with functional programming using react?

I have a controlled component which updates inputs, using functional programming, I want to know if I need do this:

class ScreensEditSeries extends Component{
constructor(props){
    super(props)  
    this.state = {
        id: '',
        name: '',
        status: '',
        genre: '',
        notes: ''
    }
}
...
handleChange = field => event => {
    this.setState({
        ...this.state,   //is necessary do this for return a new full state?
        [field] : event.target.value
    })
}
...
render(){
return(
...
                        Name: <input type="text" value={this.state.name} onChange={this.handleChange('name')} className="form-control" /><br />
                        Status: {<span>&nbsp;</span>} 
                        <select value={this.state.status} onChange={this.handleChange('status')}>
                            {Object.keys(statsuser)
                                .map( key => <option key={key}>{statsuser[key]}</option>)}
                        </select><br/><br/>
                        Genre: {<span>&nbsp;</span>} 
                        <select value={this.state.genre} onChange={this.handleChange('genre')}>
                            {Object.keys(statsgenre)
                                .map(key => <option key={key}>{statsgenre[key]}</option>)}
                        </select><br/><br/>
                        Notes: <textarea type='text' value={this.state.notes} onChange={this.handleChange('notes')} className="form-control"></textarea><br />
...
)}

I am learning functional programming, and I think it's necessary to spread the state before updating to generate a new state, and not just update it. But this requires more memory and cpu process. Is it recommend to do that?

Upvotes: 1

Views: 62

Answers (1)

Treycos
Treycos

Reputation: 7492

No, this is not necessary, setState will only modify the variables given in the JSON you provide. In your case, only the field value's attribute will be modified.

Deconstructing your state isn't needed unless you want to modify a nested property.

Upvotes: 2

Related Questions