user3348410
user3348410

Reputation: 2833

Right way using setState with redux state conditionally

I have a question about what is the best practice using setState with redux state in component

For example: I have a component with an onClick event.

In the component A's onClick event, I have dispatch some redux action which will change redux state from reducer:

someOnClickFunc = () => {
   this.props.someReduxAction()
}

and I have a component b:

import React, { Component } from 'react'
import { connect } from "react-redux";
import { bindActionCreators } from "redux";

class ComponentB extends Component {
    constructor(props) {
        super(props);
        this.state = {
          someValue: false,
        };
      }
    render() {
        return (
            <div>
                {someValue}
            </div>
        )
    }
}

const mapStateToProps = state => ({
    someReduxState: state.someReduxState
  });

  export default connect(
    mapStateToProps,
  )(ComponentB);

My component B received redux state and I want to change component self state with this redux state.

I can do it like that after render.

if (this.props.someReduxState.someVal == true) {
  this.state.someValue = true
}

But i don't want to use this.state... I prefer to use this.setState like that:

  if (this.props.someReduxState.someVal == true) {
      this.setState({
        someValue: true
      })
    }

where is the best place to do that.

When I do that after render() , or componentDidUpdate I'm getting this error:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

Upvotes: 0

Views: 1952

Answers (1)

Rohit Kashyap
Rohit Kashyap

Reputation: 1592

I believe the best way here is to use the componentDidUpdate method. But there's a catch, you need to check if the new props from the redux state are equal to the already existing props. Only then, you should proceed to mutate your state. Here's an example:

componentDidUpdate(prevProps, prevState) {
    if(prevProps.somedata.data !== this.props.somedata.data) {
              this.setState({                  //update the state after checking
                 someProperty: value
               }); 
     }
}

Upvotes: 1

Related Questions