Ali Ahmadi
Ali Ahmadi

Reputation: 731

Should i use cloned props or change props one time and make the prop into a state

I have something similar to a UIManager and a Form, i receive a fairly big JSON as props of this component, i have to iterate over this JSON and assign a onChangeFunction to each element of this JSON and then render the children using this new JSON, i will also hold the data for all the children in a state using a something like formData=[{ID:Value}] and i also update the said JSON in render using this formData so the value of children are good to go (a two way binding).
Right now i am doing this:

render () {
    let newElementList = deepClone(props.elementList)

    newElementList.forEach(element => {
      if (!element.onChange) {
        element.onChange = this.onElementChange();
      }
    })

    //use newElementList from now on
}

And i was wondering if i should do this instead:

componentDidMount() {
    let newElementList = deepClone(props.elementList)

    newElementList.forEach(element => {
      if (!element.onChange) {
        element.onChange = this.onElementChange();
      }
    })

    this.setState({elementList: newElementList});
}

render () 
{
    //use this.state.elementList from now on
}

Which is the better solution ?
Note i also do some other changes to this JSON for example i update the value parameter for each element which changes and update the JSON.

Upvotes: 0

Views: 40

Answers (1)

Mickey
Mickey

Reputation: 580

The answer would depend on where the updates to the JSON object are happening, no?

If the JSON object passed through props is just an arbitrary starting point for the component, then placing it in state on mount should suit your purposes so long as all the updates originate from this component and/or its children.

If the JSON data is being manipulated by an ancestor of this component, however, then this solution won't work since state would be set only when the component mounts, and the component would fail to reflect any changes. In that case, you'd want to continue putting together the element list in render (if you don't expect other changes to trigger a render) or in componentDidUpdate (if the component will rerendering often and you don't want to process the JSON every time).

Upvotes: 1

Related Questions