When I try to render Consumer, flow show next error:
[flow] Cannot create
SidebarContextConsumer
element because propertychangeOpenState
is missing in undefined [1] in the first argument of propertychildren
. (References: [1])
Here my code:
// @flow
import React, { createContext } from 'react';
import type { Context, ProviderProps } from './Sidebar.types';
const SidebarContext = createContext();
export const SidebarContextConsumer = SidebarContext.Consumer;
/* eslint-disable react/no-unused-state */
export class SidebarContextProvider extends React.Component<ProviderProps, Context> {
state = {
dynamic: false,
open: false,
transition: false,
changeDynamicMode: (dynamic: boolean) => {
this.setState({
dynamic,
open: false,
transition: false,
});
},
changeOpenState: (open: boolean, transition: boolean = true) => {
this.setState({ open, transition });
},
};
render() {
const { children } = this.props;
return (
<SidebarContext.Provider value={this.state}>
{children}
</SidebarContext.Provider>
);
}
}
/* eslint-enable */
Flow declaration:
export type Context = {
changeDynamicMode: (dynamic: boolean) => void,
changeOpenState: (open: boolean, transition?: boolean) => void,
dynamic: boolean,
open: boolean,
transition: boolean,
};
๐ง Re-renders reason: context changesWhen the value in Context Provider changes, all components that use this Context will re-render, even if they don't use the changed portion of the data directly.
This is the core principal of Context API, when a context value changed all components re-render. In order to prevent this we can use memo which will skip unnecessary re-renders of that component. import { memo } from "react"; const MidChild = memo(() => { console.
Before You Use Context Apply it sparingly because it makes component reuse more difficult. If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.
If you are in a situation where you need to implement some sort of library or widget system, then building on top of the Context API will give you most of what you need. And you also get the benefit of reduced bundle size, because it's already built into React.
It seems to be a known limitation of flowtype.
I resolved the error in my case with:
const SidebarContext: Object = createContext();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With