Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 27, 2022 12:51 pm GMT

Strive for a minimum required state in a React component

Keep a component state as minimal as possible and avoid unnecessary state synchronization .

Before refactoring - b is a redundant state which should be sync:

export default function App() {  const [a, setA] = useState(1);  const [b, setB] = useState(1);  function updateA(x) {    setA(x);  };  function updateB() {    setB(1 + a);  };  useEffect(() => {    updateB()  },[a])  return (    <div>      <button onClick={() => updateA(a+1)}>Click</button>        <p>a: {a}</p>        <p>b: {b}</p>    </div>)};

After refactoring - a is a minimum sufficient state and just derive b from it:

export default function App() {  const [a, setA] = useState(1);  function updateA(x) {    setA(x);  };  function updateB() {    return a+1  };  return (    <div>      <button onClick={() => updateA(a+1)}>Click</button>      <p>a: {a}</p>      <p>b: {updateB()}</p>    </div>  )};

Original Link: https://dev.to/smlka/strive-for-a-minimum-required-state-in-a-react-component-mk2

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To