๐กReact State Tips
๐ Useful lessons I've learned about Handling react state๋ฅผ ๋ณด๊ณ ์ ๋ฆฌํ ๊ธ์ ๋๋ค.
1. ์ํ(state)๋ฅผ ๋ค๋ฃจ๋ ๋ฐฉ๋ฒ๊ณผ ๊ฐ๊ฐ ํ์ํ ์ํฉ์ ์๊ณ ์๋ค.

2. ํด๋์ค ์ปดํฌ๋ํธ๋ ๋์ด์ ์ฌ์ฉํ์ง ์๋๋ค.
โ๏ธ ํจ์ํ ์ปดํฌ๋ํธ์ ์ฅ์
์ฝ๋ ์ ๊ฐ์, hooks ์ฌ์ฉ, ์ดํด ๊ฐ๋จํจ,
this
ํค์๋ ์์
3. ๊ธฐ์กด ์ํ/์์ฑ(props)๋ก๋ถํฐ ํ์๋ ์ํ(derived state)๋ฅผ ์ฌ์ฉํ๋ค.

export default function Checkout() {
const { dispatch } = useCart();
const [address, setAddress] = useState(emptyAddress);
const [satus, setStatus] = useState(STATUS.IDLE);
const [saveError, setSaveError] = useState(null);
const [touched, setTouched] = useState({});
// derived state
const errors = getErrors(address);
const isValid = Object.keys(errors).length === 0;
//...
}
4. ๐ฅ ๋ฆฌ์กํธ ๋ ๋๋ง ์์ ๊ณผ ๋ ๋๋ง ๋ฐฉ์ง๋ฒ์ ์๊ณ ์๋ค.

5. ๋๋ถ๋ถ์ ์ํ๋ ๋ฆฌ๋ชจํธ์ด๋ค.
useApi
๊ฐ์ custom hook, react-query, swr ๋ฑ์ ์ฌ์ฉํ์ฌ ๋ฆฌ๋ชจํธ ์ํ๋ฅผ ๊ฐ์ํimport React from "react"; import useFetch from "./useFetch"; export default function App() { const { data: products, loading, error } = useFetch("products"); if(loading) return "Loading..."; if(error) throw error; return // JSX }
6. ๋ก์ปฌ ์ํ๋ถํฐ ์์ํด๋ผ. ๊ธ๋ก๋ฒ ์ํ๋ ์ตํ์ ์๋จ์ด๋ค.
์์ฑ(props) ์ ๋ฌ ๊ณผ์ ์ด ๋ณต์กํด์ง๋ฉด, Context๋ Redux ์ฌ์ฉ์ ๊ณ ๋ คํด๋ณผ ์ ์๋ค.
7. Lodash, Underscore, Ramda๋ฅผ ์ฌ์ฉํ์ง ๋ง๊ณ , immutableJS
๋ฅผ ๋ฐ์๋ค์ฌ๋ผ.
immutableJS
๋ฅผ ๋ฐ์๋ค์ฌ๋ผ.โ๏ธ ์๋ฐ์คํฌ๋ฆฝํธ์์ ๋ถ๋ณ ๋ฐ์ดํฐ๋ฅผ ๋ค๋ฃจ๋ ๋ฐฉ์
Object.assign
Spread syntax:
{ ...myObj }
Immutable array methods:
.map
,.filter
,.find
,.some
,.every
,.reduce
๋ฑ
8. ํผ(form) ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ํ์ ์๋ค. ํจํด์ด ํ์ํ๋ค.

9. ๐ฅ ์ฌ๋ฌ ์ํ๋ ์ด๊ฑฐํ(enum)์ผ๋ก ์์ฑํ๋ค.
// Using seperate state to track the form's status ๐๐ป
const [submitting, setSubmitting] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [completed, setCompleted] = useState(false);
// Using a single status enum instead ๐
const STATUS = {
IDLE: "IDLE",
SUBMITTING: "SUBMITTING",
SUBMITTED: "SUBMITTED",
COMPLETED: "COMPLETED",
};
const [status, setStatus] = useState(STATUS.IDLE);
Last updated