react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

[React 19] Get context value in class component constructor

Open Lieblein opened this issue 7 months ago • 4 comments

I updated version of react from 18.2.0 to 19.1.0 (@types/react to 19.1.6, @types/react-dom to 19.1.5).

After the update I received several components with such errors:

Argument of type 'typeof SplitCostDialog' is not assignable to parameter of type 'ComponentType<never>'.
  Type 'typeof SplitCostDialog' is not assignable to type 'ComponentClass<never, any>'.
    Target signature provides too few arguments. Expected 2 or more, but got 1.

I found the reason. I use context in class constructor.

export class SplitCostDialog extends React.PureComponent<ISplitCostDialogProps, IState> {
    static contextType = ResourcePlanContext;
    declare context: IResourcePlanContext;

    constructor(props: ISplitCostDialogProps, context: IResourcePlanContext) {
        super(props);

        const { scope, position } = context.modals.splitPositionCost;
        this.state = { form: new SplitCostForm(scope, position) };
    }

    ...

}

How can I use context inside a constructor after updating to version 19? I didn't find the answer in the guide.

Lieblein avatar May 30 '25 10:05 Lieblein

Not sure how to type it correctly, but this code will work when you run it (though I think you should pass context to super too with super(props, context). @eps1lon do you know how to fix this type error?

rickhanlonii avatar Jun 02 '25 16:06 rickhanlonii

The second argument got lumped in with legacy context way back when

We also need to update docs because it won't work if you don't call super(props, context)

Technically we should require the two-parameter overload if you specify contextType. But that may be hard to ship without breaking existing code.

I'll restore the old behavior in types.

eps1lon avatar Jun 03 '25 10:06 eps1lon

Should be fixed in @types/[email protected]

eps1lon avatar Jun 09 '25 20:06 eps1lon

Thank you very much. I updated to @types/[email protected]. Everything works fine.

Lieblein avatar Jun 10 '25 05:06 Lieblein