2

I have a React class component that with an initial state object in the constructor call. I originally just had an object literal assigned to this.state, but I need to share the initial state object with other methods in the class to reset the component. Is it ok/correct to move the initial state object to be a class property and reference that in the constructor?

class SampleComponent extends Component {
  constructor() {
    super();

    this.state = this.initialState;
  }

  initialState = {
    property1: "...",
    property2: "..."
  };
}

The code seems to work, but I'm not sure if this is the right way to go about this.

gubawhips
  • 65
  • 5

1 Answers1

5

Decouple the initialState from the class:

const initialState = {
    property1: "...",
    property2: "..."
};

// As Class
class SampleComponent extends Component {
  state = initialState;
  ...
}

// Hooks
function SampleComponent(props) {
  const [myState, setMyState] = useState(initialState);
  ...
}

In this way, you avoid future bugs regarding this.initialState.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118