Skip to content

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

Open
@oscard0m

Description

@oscard0m

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:

Click to expand!**
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:

Click to expand!**
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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions