Skip to content
Advertisement

ReactJS + Typescript: Set component state with context property value without triggering a rerender

I am relatively new to ReactJS and I’m building an app with a Context. At some point I need to get one of the values from the Context, make it available for editing and only after it’s submitted change it’s value in the Context (to avoid refreshing all the other components). I thought of doing something like this:

export default class AComponent extends Component<any, { property?: Property }> {
  public constructor(props: any) {
    super(props);
  }

  public shouldComponentUpdate(nextProps: any, nextState: { property?: Property }) {
    return nextState.property !== this.state.property;
  }

  public render(): JSX.Element {
    return (
      <AContext.Consumer>
        {(data) => {
          // ...
          this.setState({ ...this.state, property: data.property });
          // ...    
        }}
      </AContext.Consumer>
    );
  }
}

But even with the shouldComponentUpdate check, it still refreshes 4 times! Without it it produces an error (recursion limit reached or something like that).

The question is: What’s the correct way of working with a context property without changing it until the moment you actually want to?

I wanted to get the Context property inside the constructor but I have found that this form is deprecated:

constructor(props: any, context: AContext) {
  super(props, context)
}

Is there any other way?

Advertisement

Answer

not only can property add to context but you can also add methods to them.

  • Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language

  • if you want to change data from different components, I prefer to use state management like Redux

    happy codeing

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement