jsx-eslint/eslint-plugin-react

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

Open

#3242 opened on Mar 12, 2022

View on GitHub
 (16 comments) (2 reactions) (0 assignees)JavaScript (8,630 stars) (2,797 forks)batch import
help wantednew rule

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.

Contributor guide