Skip to content

A React Effect that only sets state from other values ​

Code longer than it needs to be: one of the ways AI coding agents bloat software, from lessloc's pattern catalog. lessloc catches it as simpler.

What makes a React Effect that only sets state from other values a bad practice? ​

The standard that calls it a bad practice: React docs: "You Might Not Need an Effect".

What does lessloc do about a React Effect that only sets state from other values? ​

lessloc catches it as simpler.

  • simpler (tier 2): Brute-force code with a shorter idiom: == True, an if/else that returns the condition, an index loop that only reads xs[i], .filter(...).length > 0, a catch that only rethrows, a flag loop that is any(), a hand-built counter, an __init__ that @dataclass writes, a React Effect that only sets state. ruff and clippy add more.

Examples ​

Caught as simpler:

jsx
import { useEffect, useState } from "react";
export function Cart({ items }) {
  const [total, setTotal] = useState(0);
  useEffect(() => {
    setTotal(items.reduce((s, i) => s + i.price, 0));
  }, [items]);
  return <p>{total}</p>;
}

Written well:

jsx
import { useEffect, useState } from "react";
export function Theme() {
  const [theme, setTheme] = useState("light");
  useEffect(() => {
    setTheme(localStorage.getItem("theme") ?? "light");
  }, []);
  return <p>{theme}</p>;
}

The other patterns in Code longer than it needs to be:

Released under the Apache-2.0 license. · llms.txt