๐Ÿ’ก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๋ฅผ ๋ฐ›์•„๋“ค์—ฌ๋ผ.

โš™๏ธ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ ๋ถˆ๋ณ€ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค๋ฃจ๋Š” ๋ฐฉ์‹

  • 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