Engineering from Scratch

エンジニア目指してます

2022-07-01から1ヶ月間の記事一覧

getServerSideProps

Next.js は getServerSideProps によって取得したデータを使って page の pre-render を行う。 import { InferGetServerSidePropsType } from "next"; export const getServerSideProps = async (context) => { const res = await fetch("https://api.github…

useImmer

useState と同様に,state と state を更新する関数のタプル型を返す hook。state を更新する関数は,immer の produce 関数か値を引数に取れる。 immer producer function produce関数は以下のような interface となる。 produce(baseState, recipe: (draft…

Updating Objects in State

Treat state as read-only import { useState } from "react"; function App() { const [plan, setPlan] = useState({ x: 1, y: 2 }); return ( <> {plan.x} <button onClick={() => (plan.x += 1)}>a</button> ); } export default App; 上記のコードでボタンを押下しても,画面に表示され…

Choosing the State Structure

state の構造を考えるときに,考慮すべき原則は以下。 関連する state をグループ化する。 二つ以上の state を常に同時に更新しているなら,それらの state を単一の state に統合することを考えるべき。 state 間での矛盾を避ける。 冗長な state を避ける…

2022/07/21

readonly readonly のチェックがされない時がある const sum = (obj: { foo: number; bar: number; baz: number }) => { obj.foo = 999999; return obj.foo + obj.bar + obj.baz; }; const myObj = { foo: 0, bar: 100, baz: 1000, } as const; sum(myObj); …

2022/07/20

qiita.com

2022/07/19

mapped type readonly型をつけることで,書き換え不可能なものであるというインターフェースだとわかる const convertToNumberAll = (strArray: readonly string[]): number[] => { return strArray.map((str) => parseInt(str, 10)); }; const array = ["1"…

2022/07/03

You Might Not Need an Effect Resetting all state when a prop changes 悪い例 import { useEffect, useState } from "react"; const App = () => { const [userId, setUserId] = useState(0); return ( <> <button onClick={() => setUserId((userId) => userId + 1)}>+1</button> <Comment userId={userId} /> ); };</comment>…

2022/07/02

You Might Not Need an Effect props や state の変化によりコンポーネントを更新したいときに,useEffect を使うべきではない。 以下の二つの場合,useEffect を使うべきではない。 レンダリングによりデータを変換するとき。 例:あるリストを表示前にフィ…