eslint-plugin-react: False positive with no-unused-state

I’m getting a false positive:

[eslint] Unused state field: 'bar' (react/no-unused-state)

when using the following:

import React, { Component, createContext } from 'react';

export const FooContext = createContext();

export default class Foo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      bar: 'baz',
    };
  }

  render() {
    return (
      <FooContext.Provider value={this.state}>
        {this.props.children}
      </FooContext.Provider>
    );
  }
}

Is there a way to bypass this warning? (I’m using the latest version).

The following will bypass it:

<FooContext.Provider value={{ ...this.state }}>

However this will cause unintentional renders for all Context consumers

Thanks

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 6
  • Comments: 22 (10 by maintainers)

Commits related to this issue

Most upvoted comments

You should never pass the props or state objects directly. The way to satisfy the warning is to extract the state fields you want, and make a new object with them. If you want to avoid rerenders, don’t pass an object - pass flat props.

Thanks for the guidance - for me it doesn’t make sense to use multiple context providers for things that are related to the same context (in fact I already am using multiple providers). Also Memoizing a new object doesn’t really sit right with me just to satisfy this warning.

I think I’ll just disable the rule in my file for this case.

Thanks for your help though, appreciate your quick responses 😃

@callmenick indeed, but the limits of static analysis are that passing around the entire state, props, or context object makes it impossible to detect which properties are used. Since this is a bad practice anyways, though, there’s not really much value in trying to address it.

A discussion on best practices doesn’t really add anything to the original concern though, and that’s that @viralganatra is seeing a false positive whereby he’s using all the state, but the rule is telling him he isn’t.

As @jquense said though, it’s up to you folks to write the rules and such, but I think the discussion derailed pretty quickly.

come on this is bad advice, extracting and constructing a new context object in render is the anti-pattern and causes unnecessary context updates. Forcibly making all context single scalar values is a weird way around this that offers limited improvement while deepening the component tree unnecessarily. Moving the context value to a single state property artificially isn’t objectively a better option essentially when the component is only a provider, it’s state is the value.

Keeping the rule the way it is is certainly the prerogative of the project and maintainers but claiming that the react docs are actually doing it wrong, and your opinions about readability and what constitutes maintainability is FUD.