React's useState should not be directly called

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: jsx-react/usestate-direct-usage

Language: JavaScript

Severity: Error

Category: Performance

Description

This rule prevents infinite rendering loop bugs in React. The bug occurs when a hook setter function is called directly in the body of a component, because this changes the component’s state. When a component’s state is changed, re-rendering occurs.

Ensure that you do not directly call hook setter functions in components, and instead call them from an event handler.

Non-Compliant Code Examples

import { useState, useEffect } from "react";

function ShowTime() {
    const [time, setTime] = useState(new Date().toLocaleTimeString());
    setTime(new Date().toLocaleTimeString());

    return (
      <section>
        <h1>The current time is {time}</h1>
        <button onClick={() => setTime(new Date().toLocaleTimeString())}>Update Time</button>
      </section>
    );
}

Compliant Code Examples

import { useState, useEffect } from "react";

function ShowTime() {
    const [time, setTime] = useState(new Date().toLocaleTimeString());

    useEffect(() => {
        const timer = setInterval(() => {
            setTime(new Date().toLocaleTimeString());
        }, 1000);

        return () => clearInterval(timer);
    }, []);

    return (
      <section>
        <h1>The current time is {time}</h1>
        <button onClick={() => setTime(new Date().toLocaleTimeString())}>Update Time</button>
      </section>
    );
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: rtrieu/product-analytics-ui-changes