Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common code in React component constructor and componentWillReceiveProps

I often come to this sort of situation when using statefull React components.

I need to do some operation on props - either do some processing which I do now want to have in render() or set state according the values in props.

As I want to do this when component is initially mounted as well as when the props are updated, I end up with a boilerplate code like this:

constructor(){
    super(props)
    const modifiedProps = doSomethingWithProps(props)
        ...
    this.state = {initialState}
}

componentWillReceiveProps(nextProps) {
    const modifiedProps = doSomethingWithProps(nextProps)
         ...
    this.setState({newState})
}

doSomethingWithProps(props){
        ...
}

Is there a better way how to do this ?

like image 326
ps-aux Avatar asked Oct 29 '22 06:10

ps-aux


1 Answers

Answering based on the question's comments, which I found quite helpful --

If there's a bunch of work that needs to be done based on props, componentWillMount allows you to use this.setState() in your helper functions and minimize the work that's done in the constructor. This can clean up a bunch of otherwise duplicated code.

constructor(){
    super(props)
    this.state = {initialState}
}

componentWillMount() {
    this.doSomethingWithProps(this.props);
}

componentWillReceiveProps(nextProps) {
    this.doSomethingWithProps(nextProps)
}

doSomethingWithProps(props){
    ...
    this.setState({newState})
}
like image 131
lambinator Avatar answered Nov 13 '22 05:11

lambinator