Skip to content Skip to sidebar Skip to footer

Where Is The Best Place To Put A Value Which Is Computed Once By The Initial Passed-in Parameter And Never Changed Again, In Reactjs?

In a reactjs component, I will compute a value based on the passed-in parameter, which will never changed again. Say: React.createClass({ componentWillMount: function() {

Solution 1:

The rule of thumb is render should be derived from props and state. Because you can't change your props, I'd put it in state.

React.createClass({
    componentWillMount: function() {
        this.setState({
            computedValue: complexComputing(this.props.feed)
        });
    },
    render: function() {
        return<div>{this.state.computedValue}</div>
    }
});

Putting things on this is correct if you just want to share data between lifecycle methods, most commonly to make things available for cleanup in componentWillUnmount.

Solution 2:

You're in one of the right methods for these types of computations.

According to a React components life cycle there is a few methods that only gets invoked once and only once and they are getInitialState(), getDefaultProps(), componentWillMount() and componentDidMount().

I would however put it in getDefaultProps() since it makes more sense to have this type of data there since it's data that you don't want to mutate via state.

Post a Comment for "Where Is The Best Place To Put A Value Which Is Computed Once By The Initial Passed-in Parameter And Never Changed Again, In Reactjs?"