Vue.jsからはじめるReact

2.1K Views

July 18, 25

スライド概要

Vue.jsからフロントエンド開発に入った人に向けて、Reactを書くにあたってのメンタルモデルの違いを理解できるようにします。

シェア

またはPlayer版

埋め込む »CMSなどでJSが使えない場合

ダウンロード

関連スライド

各ページのテキスト
1.

Vue.jsからはじめるReact ashphy @[email protected]

2.

今日の目標 • Vue.jsとの比較からReactのメンタルモデルの違いを理解する

3.

おことわり • Vue 3.5を知ってることを前提とする • Vapor Modeは触れない • VueとReactどちらが優れているかという議論は行わない • Reactを知っている人には新しい情報はない

4.

どの範囲がレンダリングされるか? ボタンを押したときにどの範囲が再レンダリングされるでしょうか?

5.

どの範囲がレンダリングされるか? • ReactとVueのコード

6.

Vue 親コンポーネントのみが再レンダリングされる

7.

React 親子の両方が再レンダリングされる

8.

Reactは子要素も再レンダリングされる レンダーとコミット ‒ React

9.

Reactは全体を再レンダリング • 差分が発生した要素からすべて再レンダリングしていく • 何が変わったのかではなく、今の状態に対するUIを計算する

10.

Vueは変化した要素だけ再レンダリング • Vueは状態(state)が使われたコンポーネントを追跡している = Signals

11.

Vueはなぜ変化したコンポーネントだけ 再レンダリングできるのか?

12.

ref と useState Vue const count = ref(0); Refオブジェクト const increment = () => { count.value++; }; React const [count, setCount] = useState(0); 値 更新関数 const increment = () => { setCount((prev) => prev + 1); };

13.

refの実装 (擬似コード) const myRef = { _value: 0, get value() { 状態の仕様を追跡 track() return this._value }, set value(newValue) { this._value = newValue trigger() } 状態の変更を通知 } プロパティアクセスで状態の使用状況を追跡

14.

reactiveの実装 (擬似コード) const reactive(target) { const handler = { 状態の仕様を追跡 get(obj, key, receiver) { track(obj, key); return Reflect.get(obj, key, receiver); }, set(obj, key, value, receiver) { const oldValue = obj[key]; const result = Reflect.set(obj, key, value, receiver); if (oldValue !== value) { trigger(obj, key); } 状態の変更を通知 return result; } }; return new Proxy(target, handler); プロキシを返す }

15.
[beta]
分割代入でリアクティブでなくなる
<script setup lang="ts">
const count = ref(0);
const { value } = count;
const increment = () => {
count.value++;
};
</script>

リアクティブでなくなる

<template>
<div>Count: {{ value }}</div>
<button @click="increment">Increment</button>
</template>

16.
[beta]
computed
Vue
const firstName = ref('John’)
const lastName = ref('Doe’)
const fullName = computed(() => {
return `${firstName.value} ${lastName.value}`
})
React
const [firstName, setFirstName] = useState('John’);
const [lastName, setLastName] = useState('Doe’);
const fullName = `${firstName} ${lastName}`;
コンポーネント本体で宣言された変数はすべてリアクティブである.
※ computedはメモ化するので正確にはuseMemoが必要

17.

Reactは純粋性(purity)を重視する • 純粋なコンポーネントやフックとは • べき等である • 同じ入力 (props, state, context) で常に同じ結果が得られること • レンダー時に副作用がない • 副作用はレンダー以外のイベントハンドラなどで実行される必要がある • ローカルな値以外を更新しない

18.

宣言型UI UI = 𝑓(𝑥)

19.

宣言型UI props, state, context UI = 𝑓(𝑥) コンポーネント 同じ入力 (props, state, context) で常に同じ結果が得られる

20.

ref と useState Vue const count = ref(0); Refオブジェクト const increment = () => { count.value++; }; stateはmutable React const [count, setCount] = useState(0); 値 更新関数 const increment = () => { setCount((prev) => prev + 1); }; stateはimmutable

21.

純粋であるとなにがいいのか? • 安全にキャッシュできる • どの順番で計算しても良い • レンダーを中断してもいい • サーバでも実行できる

22.

Reactのレンダリング • レンダー (Rendering) • Reactがコンポーネントを呼び出すこと • コミット (Commit) パッチ(Patch) • ReactがDOMノードを更新すること • ペイント (Paint) • ブラウザがDOMを画面に描画すること

23.

useStateの値はすぐには更新されない • state はスナップショットである

24.

stateはスナップショットである • state をセットしても、既にある state 変数は変更されず、 代わりに再レンダーがトリガされる。

25.

watch, watchEffect • watch • 監視するソースを自分で指定できる • once: true • 一度だけ実行できる • immediate: true • 強制的に即時実行できる コールバックをいつ実行するのか 正確にコントロールできる

26.

useEffect • コンポーネントを外部システムと同期させるためのフック • useEffectには同期を開始する処理と終了する処理のみを記載 する

27.

ライフサイクルフック • onMounted, onUpdated, onUnmounted => useEffect • コンポーネントが現在マウント、更新、アンマウントのどれを 行っているかを考慮すべきではない

28.
[beta]
useEffectの例
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState("https://localhost:1234");
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
}

29.
[beta]
useEffectの例
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState("https://localhost:1234");
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
セットアップコード
connection.disconnect();
};
}, [serverUrl, roomId]);
}

30.
[beta]
useEffectの例
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState("https://localhost:1234");
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
クリーンアップコード
}, [serverUrl, roomId]);
}

31.
[beta]
useEffectの例
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState("https://localhost:1234");
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
}
依存配列 リアクティブな値を指定する

32.

useEffect • useEffectは開発中に2回実行される • 開発中のみコンポーネント、useState、set関数、useMemo、 useReducerも2回呼ばれる • コンポーネントが純粋なら「何回呼び出されても結果は同じ」 はずなので、2回呼んでみる

33.

state 再利用可能性の保証 • 将来的にReactがstateを保ったままで一部分の追加、削除で きるような機能を導入する • → オフスクリーン • コンポーネントは複数回のmount/unmountに耐える必要が ある

34.

Composables • hooks • ルール • ループ、条件分岐、ネストされた関数、try/catch/finallyブロック の内側で呼び出してはいけない • 早期 return を行う前に呼び出す • Reactの関数からのみ呼ぶことができる

35.

useStateは呼び出しの順番に依存する • useStateには識別子を渡さない代わりに順番で管理される • <setup script>は一度だけ呼び出されるので管理する必要が ない

36.
[beta]
stale closure
Vue
<script setup>
const count = ref(0)
function handleClick() {
setTimeout(() => {
alert(count.value)
}, 1000)
}
</script>
<template>
<button @click="handleClick">
Click me
</button>
</template>

React
const Component() {
const [count, setCount] = useState(0);
const handleClick = () => {
setTimeout(() => {
alert(count);
}, 1000);
};
return <button onClick={handleClick}>
Click me
</button>;
}

37.
[beta]
stale closure
Vue
<script setup>
const count = ref(0)
function handleClick() {
setTimeout(() => {
alert(count.value)
}, 1000)
}
</script>
<template>
<button @click="handleClick">
Click me
</button>
</template>

React
クロージャ (閉包環境)
const Component() {
const [count, setCount] = useState(0);
const handleClick = () => {
setTimeout(() => {
alert(count);
}, 1000);
};
return <button onClick={handleClick}>
Click me
</button>;
}

38.
[beta]
stale closure
Vue
<script setup>
const count = ref(0)
function handleClick() {
setTimeout(() => {
alert(count.value)
}, 1000)
}
</script>
<template>
<button @click="handleClick">
Click me
</button>
</template>

React
クロージャ (閉包環境)
const Component() {
const [count, setCount] = useState(0);
const handleClick = () => {
レキシカル環境
setTimeout(() => {
alert(count);
}, 1000);
};
return <button onClick={handleClick}>
Click me
</button>;
}

39.
[beta]
stale closure
Vue
<script setup>
const count = ref(0)
function handleClick() {
setTimeout(() => {
alert(count.value)
}, 1000)
}
</script>
<template>
<button @click="handleClick">
Click me
</button>
</template>

React
クロージャ (閉包環境)
const Component() {
const [count, setCount] = useState(0);
const handleClick = () => {
レキシカル環境
setTimeout(() => {
束縛 (capture)
alert(count);
}, 1000);
};
return <button onClick={handleClick}>
Click me
</button>;
}

40.
[beta]
stale closure
Vue
<script setup>
const count = ref(0)
function handleClick() {
setTimeout(() => {
alert(count.value)
}, 1000)
}
</script>
<template>
<button @click="handleClick">
Click me
</button>
</template>

React
クロージャ (閉包環境)
const Component() {
const [count, setCount] = useState(0);
const handleClick = () => {
レキシカル環境
setTimeout(() => {
束縛 (capture)
alert(count);
}, 1000);
};
return <button onClick={handleClick}>
Click me
</button>;
}
レンダリング時の古い(stale)値に束縛される

41.
[beta]
stale closure
Vue
<script setup>
const count = ref(0)
function handleClick() {
setTimeout(() => {
alert(count.value)
}, 1000)
}
</script>
実行時の値に束縛されるが、
<template>
Refオブジェクトを通じて最新の値にアクセスできる
<button @click="handleClick">
Click me
</button>
</template>

React
クロージャ (閉包環境)
const Component() {
const [count, setCount] = useState(0);
const handleClick = () => {
レキシカル環境
setTimeout(() => {
束縛 (capture)
alert(count);
}, 1000);
};
return <button onClick={handleClick}>
Click me
</button>;
}
レンダリング時の古い(stale)値に束縛される

42.

props Vue <script setup> const props = defineProps<{ count: number }>() const { count } = props </script> React type Props = { count: number; }; export function Counter({ count }: Props) { return <p>Count: {count}</p>; } <template> <p>Count: {{ count }}</p> </template> Reactでは引数として表現される

43.
[beta]
propsの分割代入
Vue
<script setup>
const { foo } = defineProps(['foo'])
watchEffect(() => {
// 3.5 以前は 1 回だけ実⾏される
console.log(foo)
})
</script>
const props = defineProps(['foo'])
watchEffect(() => {
console.log(props.foo)
})

React
type Props = {
count: number;
};
export function Counter(props: Props) {
const { count } = props;
return <p>Count: {count}</p>;
}

Reactはただの値なのでどこで分割代入しても良い

44.
[beta]
emit
Vue
<script setup>
const emit = defineEmits(["customClick"]);
function handleClick() {
emit("customClick", "Hello!");
}
</script>
<template>
<button @click="handleClick">
Click me
</button>
</template>

React
type Props = {
onCustomClick: (message: string) => void;
};
function Component({ onCustomClick }: Props) => {
const handleClick = () => {
onCustomClick("Hello!");
};
return <button onClick={handleClick}>
Click me
</button>;
};

ReactではイベントはPropsで渡す

45.
[beta]
フォールスルー属性
• Reactにはない 明示的に宣言される
import type { ButtonHTMLAttributes } from "react";
type MyButtonProps = ButtonHTMLAttributes<HTMLButtonElement>;
function MyButton({ className, ...rest }: MyButtonProps) {
return (
<button className={`base-class ${className ?? ""}`} {...rest} />
);
}

46.
[beta]
slot
Vue
<template>
<button class="btn">
<slot></slot>
</button>
</template>

React
type Props = {
children: React.ReactNode;
};
function Button({ children }: Props) {
return <button className="btn">
{children}
</button>;
}

47.
[beta]
名前付きslot
Vue
<template>
<button class="btn">
<span class="icon">
<slot name="icon"></slot>
</span>
<span class="label">
<slot></slot>
</span>
</button>
</template>

React
type Props = {
icon?: React.ReactNode;
children: React.ReactNode;
};
export function Button({ icon, children }: Props) {
return (
<button className="btn">
{icon && <span className="icon">{icon}</span>}
<span className="label">{children}</span>
</button>
);
}

属性のひとつとして渡すことができる

48.
[beta]
defineModel
• ない 明示的に宣言される
Vue
<script setup>
const modelValue = defineModel<string>()
</script>
<template>
<input v-model="modelValue" />
</template>

React
type Props = {
value: string;
onChange: (value: string) => void;
};
const Input = ({ value, onChange }: Props) => (
<input
value={value}
onChange={(e) => onChange(e.target.value)}
/>
);

49.

どうやってパフォーマンスを 改善すれば良いか?

50.

メモ化 Memorization • 関数の呼び出し結果を保存しておいて、後の呼び出しで利用し 再計算を防ぐ const [firstName, setFirstName] = useState("John"); const [lastName, setLastName] = useState("Doe"); const fullName = useMemo( () => `${firstName} ${lastName}`, [firstName, lastName] ); 依存配列に指定された値が変わると再計算される

51.

コンポーネントもメモ化 • propsが変わらなければレンダリングをスキップする const MemoizedComponent = memo((props) => { // ... });

52.
[beta]
コンポーネントのメモ化が効かない例
interface ChildProps { onClick: () => void; }
const Child = memo(({ onClick }: ChildProps) => {
return <button onClick={onClick}>Increment</button>;
});
const Parent = () => {
const [count, setCount] = useState(0);
return (<>
<p>Count: {count}</p>
<Child onClick={() => setCount((c) => c + 1)} />
</>);
};

53.
[beta]
コンポーネントのメモ化が効かない例
interface ChildProps { onClick: () => void; }
const Child = memo(({ onClick }: ChildProps) => {
return <button onClick={onClick}>Increment</button>;
});
const Parent = () => {
const [count, setCount] = useState(0);
return (<>
<p>Count: {count}</p>
<Child onClick={() => setCount((c) => c + 1)} />
</>);
};
レンダリングのたびに関数が生成される

54.
[beta]
コンポーネントのメモ化が効かない例
interface ChildProps { onClick: () => void; }
const Child = memo(({ onClick }: ChildProps) => {
return <button onClick={onClick}>Increment</button>;
});
const Parent = () => {
const [count, setCount] = useState(0);
return (<>
<p>Count: {count}</p>
<Child onClick={() => setCount((c) => c + 1)} />
</>);
};

55.
[beta]
useCallback
• 再レンダー間で関数定義をキャッシュできるようにするフック
const Parent = () => {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount((c) => c + 1);
}, []);
return ( <>
<p>Count: {count}</p>
<Child onClick={handleClick} />
</> );
};

56.

子要素をchildrenとして受け取る • Render-as-children Sample

57.

でもめんどくさくない?

58.

React Compiler • Reactアプリを自動的に最適化する • 自動でuseMemo, useCallbackを挿入する • React Compiler Playground で試せる • 10月のReact Conf 2025でリリースされるかも…?

59.
[beta]
コンパイル結果
export default function MyApp() {
return <div>Hello World</div>;
}

import { c as _c } from "react/compiler-runtime";
export default function MyApp() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = <div>Hello World</div>;
$[0] = t0;
初回は要素を生成する
} else {
t0 = $[0];
}
return t0;
}

60.
[beta]
コンパイル結果
export default function MyApp() {
return <div>Hello World</div>;
}

import { c as _c } from "react/compiler-runtime";
export default function MyApp() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = <div>Hello World</div>;
$[0] = t0;
キャッシュする
} else {
t0 = $[0];
}
return t0;
}

61.
[beta]
コンパイル結果
export default function MyApp() {
return <div>Hello World</div>;
}

import { c as _c } from "react/compiler-runtime";
export default function MyApp() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = <div>Hello World</div>;
$[0] = t0;
} else {
t0 = $[0];
次回以降キャッシュを返す
}
return t0;
}

62.

組み合わせるライブラリ

63.

状態管理ライブラリ - Pinia • React • Jotai • Zustand • Valtio • おそらく一番Piniaに近い • Redux • 忘れていい

64.

データ取得ライブラリ • useFetch (Nuxt) • Vite • TanStack Routerのloader • TanStack Query • Next.js • fetch (Next.jsが提供するfetchは魔改造されてる) • SWR • Vue Query • TanStack Query

65.

ルーティング ‒ Vue Router • React Router • TanStack Router

66.

フォーム管理ライブラリ • React Hook Form • シェアが一番多い • Conform • ドキュメントに日本語がある • TanStack Form • Vue版もあるので慣れてるならこれでいい • (あまり好きではない)

67.

Composition Utilities - VueUse • useHooks • usehooks-ts • @react-hookz/web

68.

まとめ • React • 全体を高速に再レンダリングする • すべてのコンポーネント、フックは純粋であると仮定

69.

参考文献 • LEARN REACT • リアクティビティーの探求 • React Labs: 私達のこれまでの取り組み - 2022年6月版 • JavaScript Signals standard proposal

70.

参考文献 • "React Core Panel" by Joe Savona, Ricky Hanlon, Dan Abramov, & Michael Jackson at #RemixConf 2023 💿