惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

腾讯CDC
The Cloudflare Blog
IT之家
IT之家
V
V2EX
雷峰网
雷峰网
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
Stack Overflow Blog
Stack Overflow Blog
博客园 - Franky
Engineering at Meta
Engineering at Meta
S
SegmentFault 最新的问题
GbyAI
GbyAI
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
小众软件
小众软件
博客园 - 叶小钗
Blog — PlanetScale
Blog — PlanetScale
C
Check Point Blog
A
About on SuperTechFans
B
Blog
月光博客
月光博客
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
React.js ~useState Antipatterns~
Ogasawara Kakeru · 2026-06-21 · via DEV Community
Cover image for React.js ~useState Antipatterns~

Ogasawara Kakeru

1. Consider grouping related conditions together

  • Before
  const [x, setX] = useState(0);
  const [y, setY] = useState(0);

  const handlePointerMove = (e) => {
    setX(e.clientX);
    setY(e.clientY);
  };
  return (
      <div
        onPointerMove={handlePointerMove}
        style={{
          width: "100vw",
          height: "100vh",
        }}
      />
  );

  • After
 const [position, setPosition] = useState({ x: 0, y: 0 });

 const handlePointerMove = (e) => {
    setPosition({
      x: e.clientX,
      y: e.clientY,
    });
  };
  return (...
  );

  • Before
const [userName, setUserName] = useState("");
const [userAge, setUserAge] = useState(0);

  • After
const [userInfo, setUserInfo] = useState({name:"",age:0});

2. Avoid declaring conflicting states

  • Before
export default function Form() {
  const [text, setText] = useState('');
  const [isSubmitting, setSubmitting] = useState(false);
  const [isSubmit, setIsSubmit] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    isSubmitting(true);
    await sendMessage(text);
    isSubmitting(false);
    setIsSubmit(true);
  }

  if (isSubmit) {
    return <h1>I appreciate</h1>
  }

  function sendMessage(text) {
    return new Promise(resolve => {
    setTimeout(resolve, 2000);
   });
  }

  return (
    <form onSubmit={handleSubmit}>
      <textarea
        disabled={isSending}
        value={text}
        onChange={e => setText(e.target.value)}
      />
      <br />
      <button
        disabled={isSending}
        type="submit"
      >
        Submit
      </button>
      {isSubmitting && <p>Submitting...</p>}
    </form>
  );
}

  • After
export default function Form() {
  const [text, setText] = useState('');
  const [status, setStatus] = useState('TYPING');

  async function handleSubmit(e) {
    e.preventDefault();
    setStatus('SUBMITTING');
    await sendMessage(text);
    setStatus('SUBMITTED');
  }

  const isSending = status === 'SUBMITTING';
  const isSent = status === 'SUBMITTED';

  return (...
  );
}

isSubmit and isSubmitting are conflicting and make it difficult to handle these states as it gets complex.
You have to group them into a single state.

3. Avoid redundant use

export default function Form() {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [fullName, setFullName] = useState('');

  function handleFirstNameChange(e) {
    setFirstName(e.target.value);
    setFullName(e.target.value + ' ' + lastName);
  }

  function handleLastNameChange(e) {
    setLastName(e.target.value);
    setFullName(firstName + ' ' + e.target.value);
  }

  return (
    <>
      <label>
        First name:
        <input
      name="firstName"
          value={firstName}
          onChange={handleFirstNameChange}
        />
      </label>
      <label>
        Last name:
        <input
      name="lastName"
          value={lastName}
          onChange={handleLastNameChange}
        />
      </label>
      <p>
        FullName: <span>{fullName}</span>
      </p>
    </>
  );
}

The fullName can be calculated when rendering by firstName + lastName.

  const [userName, setUserName] = useState({ firstName: "", lastName: "" });
  const fullName = userName.firstName + " " + userName.lastName;

  const handleUserNameChange = (e) => {
    setUserName({ ...userName, [e.target.name]: e.target.value });
  };

And props should not be held in the state.

function Text({ children, color }) {
  const [textColor] = useState(color);

  return <h1 style={{ color: textColor }}>{children}</h1>;
}

export default function Example() {
  const [color, setColor] = useState("red");

  return (
    <div>
      <p>
        Select Color
        <select value={color} onChange={(e) => setColor(e.target.value)}>
          <option value="red">Red</option>
          <option value="blue">Blue</option>
          <option value="green">Green</option>
        </select>
      </p>
      <Text color={color}>Color will be changed</Text>
    </div>
  );
}

The color seems to change at a glance, but doesn't change.
Because useState is initialized when first rendering.

  • Fixed
function Text({ children, color }) {
  const textColor = color;

  return <h1 style={{ color: textColor }}>{children}</h1>;
}

4. Avoid declaring the same state multiple times

const initialItems = [
  { id: 1, title: "taskA" },
  { id: 2, title: "taskB" },
  { id: 3, title: "taskC" },
];

export default function TaskList() {
  const [tasks, setTasks] = useState(initialItems);
  const [selectedTask, setSelectedTask] = useState(tasks[0]);

  function handleTaskChange(id, e) {
    setTasks(tasks.map((task) => (task.id === id ? { ...task, title: e.target.value } : task)));
    setSelectedTask((task) => (task.id === id ? { ...task, title: e.target.value } : task));
  }

  return (
    <>
      <h2>Task List</h2>
      <ul>
        {tasks.map((task, index) => (
          <li key={task.id}>
            <input
              value={task.title}
              onChange={(e) => {
                handleTaskChange(task.id, e);
              }}
            />
            <button
              onClick={() => {
                setSelectedTask(task);
              }}
            >
              Select
            </button>
          </li>
        ))}
      </ul>
      <p>Today's task {selectedTask.title}</p>
    </>
  );
}

The task and the selectedTask handle the same data.
When you edit the task, you have to update selectedTask.

So, fix the codebase to calculate the selectedTask by id

function TaskList() {
  const [tasks, setTasks] = useState(initialItems);
  const [selectedTaskId, setSelectedTaskId] = useState(0);

  function handleTaskChange(id, e) {
    setTasks(tasks.map((task) => (task.id === id ? { ...task, title: e.target.value } : task)));
  }

  const selectedTask = tasks.find((task) => task.id === selectedTaskId);

  return (
    <>
      <h2>Task List</h2>
      <ul>
        {tasks.map((task) => (
          <li key={task.id}>
            <input
              value={task.title}
              onChange={(e) => {
                handleTaskChange(task.id, e);
              }}
            />
            <button
              onClick={() => {
                setSelectedTaskId(task.id);
              }}
            >
              Select
            </button>
          </li>
        ))}
      </ul>
      <p>Today's Task {selectedTask.title}</p>
    </>
  );
}