jsx-eslint/eslint-plugin-react

Is there an ESLint rule to error/warn to avoid "Mirroring props in state"?

Open

#3 242 ouverte le 12 mars 2022

Voir sur GitHub
 (16 commentaires) (2 réactions) (0 assignés)JavaScript (2 797 forks)batch import
help wantednew rule

Métriques du dépôt

Stars
 (8 630 stars)
Métriques de merge PR
 (Aucune PR mergée en 30 j)

Description

Description*

I would like to know if there is any existing ESLint rule this plugin for preventing mirroring props in state

❌ Do not use a prop as the initial useState() value:

const ParentComponent = () => {
const [initialValue, setInitialValue] = useState("Initial value");

useEffect(() => {
    setTimeout(() => {
      setInitialValue("Changed value");
    }, 1000);
  }, []);

  return <ChildComponent initialValue={initialValue} />;
};

const ChildComponent = ({ initialValue }) => {
  const [inputValue, setInputValue] = useState(initialValue);

  const handleChange = (e) => {
    setInputValue(e.target.value);
  };

  return <input value={inputValue} onChange={handleChange} />;
};

✅ Use useEffect() instead to fix it:

import React, { useState, useEffect } from "react";

const ParentComponent = () => {
  const [initialValue, setInitialValue] = useState("Initial value");

  useEffect(() => {
    setTimeout(() => {
      setInitialValue("Changed value");
    }, 1000);
  }, []);

  return <ChildComponent initialValue={initialValue} />;
};

const ChildComponent = ({ initialValue }) => {
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    if (initialValue) {
      setInputValue(initialValue);
    }
  }, [initialValue]);

  const handleChange = (e) => {
    setInputValue(e.target.value);
  };

  return <input value={inputValue} onChange={handleChange} />;
};

Context

It's something React Docs (beta) suggests:

https://beta.reactjs.org/learn/choosing-the-state-structure#avoid-redundant-state -> check Deep Dive box

image

Notes

  • *If there is not an existing ESLint rule for this and you think it could have sense I will edit the title and the issue description
  • **Thanks to @volodymyrhudyma since I used his awesome article example to illustrate the issue.

Guide contributeur