jsx-eslint/eslint-plugin-react

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

Open

#3242 aperta il 12 mar 2022

Vedi su GitHub
 (16 commenti) (2 reazioni) (0 assegnatari)JavaScript (2797 fork)batch import
help wantednew rule

Metriche repository

Star
 (8630 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

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.

Guida contributor