AI Bültenim Yapay Zeka Haber Portalı Logosu
Kod

Sınıftan hook refaktörü

Class bileşenini hook’lara güvenli şekilde taşır.

Kod Prompt Kütüphanesi için temsili kategori görseli

Prompt Metni

Aşağıdaki sayaç bileşenini public props API'sini değiştirmeden functional component ve hook yapısına dönüştür. Davranış farklarını kısaca açıkla.

class Counter extends React.Component<{ initial: number }, { count: number }> {
  state = { count: this.props.initial }
  componentDidUpdate(_: unknown, previous: { count: number }) {
    if (previous.count !== this.state.count) document.title = String(this.state.count)
  }
  render() {
    return <button onClick={() => this.setState(({ count }) => ({ count: count + 1 }))}>{this.state.count}</button>
  }
}

Prompt Sonucu

import { useEffect, useState } from 'react' type CounterProps = { initial: number } export function Counter({ initial }: CounterProps) { const [count, setCount] = useState(initial) useEffect(() => { document.title = String(count) }, [count]) return ( <button onClick={() => setCount((current) => current + 1)}> {count} </button> ) } Davranış notu: - initial yalnızca ilk render sırasında state'i belirler; sonradan değişmesi sayacı sıfırlamaz. - useEffect ilk render sonrasında da çalışır. Sınıf örneğindeki componentDidUpdate ise ilk render sırasında çalışmaz. İlk render davranışının birebir korunması gerekiyorsa bir useRef ile ilk effect atlanabilir.

AI Bültenim prompt kütüphanesi — Tüm promptlar