Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New React context API and flow error, when trying to render Consumer

When I try to render Consumer, flow show next error:

[flow] Cannot create SidebarContextConsumer element because property changeOpenState is missing in undefined [1] in the first argument of property children. (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,
};

People also ask

Does New React context API trigger re-renders?

๐Ÿง 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.

How can I avoid component re use problem with context API?

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.

What's wrong with using context in React?

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.

In which of the following cases is it advisable to use the React context API?

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.


1 Answers

It seems to be a known limitation of flowtype.

I resolved the error in my case with:

const SidebarContext: Object = createContext();
like image 147
Shammoo Avatar answered Oct 04 '22 21:10

Shammoo