JSXの基本
式と属性
const name = "Alice"; const el =

Hello, {name}!

; const img = photo;
JSXのルール
{expression}任意のJS式を埋め込む
classNameclassの代わりに使用
htmlForforの代わりに使用
style={{color: 'red'}}インラインスタイルをオブジェクトで指定
<Component />自己閉じタグが必須
<> ... </>フラグメント(余分なDOMノードなし)
コンポーネント
関数コンポーネント
function Greeting({ name }) { return

Hello, {name}!

; } // Arrow function variant const Greeting = ({ name }) => (

Hello, {name}!

);
Props
function Card({ title, children }) { return (

{title}

{children}
); }

Content here

デフォルトProps
function Button({ label = "Click me", onClick }) { return ; }
状態(useState)
基本的な状態
import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( ); }
関数型の更新
setCount(prev => prev + 1); // use prev state setItems(prev => [...prev, newItem]); // arrays setUser(prev => ({...prev, name: "Bob"})); // objects
状態のルール
Immutable updates状態を直接変更しない
Async batching更新はバッチ処理される場合がある
Functional form前の状態に依存する場合はprev =>を使用
エフェクト(useEffect)
エフェクトのパターン
import { useEffect } from "react"; // Run on every render useEffect(() => { /* ... */ }); // Run once on mount useEffect(() => { /* ... */ }, []); // Run when deps change useEffect(() => { /* ... */ }, [count]); // Cleanup on unmount useEffect(() => { const id = setInterval(tick, 1000); return () => clearInterval(id); }, []);
リストとキー
function TodoList({ items }) { return ( ); }

キーは安定したユニークIDにする — 配列インデックスはキーとして使わない

イベント処理
イベント
setVal(e.target.value)} />
{ e.preventDefault(); handleSubmit(); }}>
よく使うイベント
onClickマウスクリック
onChange入力値の変更
onSubmitフォームの送信
onKeyDownキー押下
onFocus / onBlurフォーカス取得 / 喪失
onMouseEnterマウスが要素に入る
条件付きレンダリング
// Ternary {isLoggedIn ? : } // Logical AND (short-circuit) {hasError && } // Early return function Page({ user }) { if (!user) return ; return ; }
フック
useRef
const inputRef = useRef(null); // Access: inputRef.current.focus();

useRefは再レンダリングをトリガーせずにレンダリング間で値を保持する

useMemoとuseCallback
// Memoize expensive computation const sorted = useMemo( () => items.sort(compareFn), [items] ); // Memoize callback const handleClick = useCallback( () => setCount(c => c + 1), [] );
useContext
import { useContext } from "react"; const value = useContext(MyContext);
カスタムフック
function useLocalStorage(key, initial) { const [value, setValue] = useState(() => { const saved = localStorage.getItem(key); return saved ? JSON.parse(saved) : initial; }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; } // Usage const [name, setName] = useLocalStorage("name", "");

カスタムフックは'use'で始まる名前にする必要がある

Context API
作成とプロバイダー
import { createContext, useContext } from "react"; const ThemeCtx = createContext("light"); function App() { return ( ); }
消費
function Page() { const theme = useContext(ThemeCtx); // "dark" return
...
; }