Right way using setState with redux state conditionally

avatar
9    2 months ago

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

eg: i have one component with some onClick event.

in component A 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 wan't 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 i
Answers { 1 }
avatar
2 months ago

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
               }); 
     }
}