https://react.dev/learn/choosing-the-state-structure
๋ฆฌ์กํธ์์ ์ํ ๊ตฌ์กฐ๋ฅผ ์งค ๋์ ์์น๋ค์ ๋ํด์ ์๊ฐํ๋ ์น์ ์ด๋ค. DB์ ์ ๊ทํ์ฒ๋ผ ์ค์๋ ๋ฒ๊ทธ๊ฐ ๋ฐ์ํ ๋ถ๋ถ์ ์ค์ด๋ ๊ฒ์ด ๋ชฉ์ ์ด๋ค.
- Group related state
// BAD
const [x, setX] = useState(0);
const [y, setY] = useState(0);
// GOOD
const [position, setPosition] = useState({x:0, y:0});- Avoid contradictions in state
// BAD
const [isSending, setIsSending] = useState(false);
const [isSent, setIsSent] = useState(false);
// GOOD
const [status, setStatus] = useState("typing");
const isSending = status === "sending";
const isSent = status === "sent";- BAD์์๋ `isSending`๊ณผ `isSent`๋ผ๋ ์๋ฐ๋ ์ํ๋ฅผ ๋์๋ค. ๋์์ ํ๊ฒ ์ง๋ง, ์ค์๋ก ํ๊ฐ์ง ์ํ๋ฅผ ์
๋ฐ์ดํธ ํ์ง ์๋ ๊ฒฝ์ฐ๊ฐ ๋ฐ์ํ ์ ์๋ค.
- ๋ฐ๋ผ์ GOOD์์์ ๊ฐ์ด status๋ฅผ ๋ํ๋ด๋ ํ๋์ ์ํ๋ฅผ ๋ง๋ค๊ณ , isSending๊ณผ isSent๋ ๊ทธ status์ ๋ฐ๋ผ ๊ฐ์ด ์๋์ผ๋ก ์
๋ฐ์ดํธ ๋๋๋กํ์๋ค.
- Avoid redundant in state : props๋ ๋ค๋ฅธ ์ํ๋ค๋ก๋ถํฐ ๊ณ์ฐ์ด ๊ฐ๋ฅํ ๊ฐ์ ์ํ๋ก ์ง์ ํ์ง ๋ง๋ผ
// BAD
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [fullName, setFullName] = useState("");
// GOOD
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const fullName = firstName + ' ' + lastName;- Avoid duplication in state
// BAD
const [items, setItems] = useState(initialItems);
const [selectedItem, setSelectedItem] = useState(initialItems[0]);
// GOOD
const [items, setItems] = useState(initialItems);
const [selectedId, setSelectedId] = useState(0);- BAD์์๋ items์ ๋ด๊ธด ์์ ์ค ํ๋๋ฅผ selectedItem์๋ ๊ฐ์ง๊ณ ์๋ค. ์ด๋ ๊ฒ ๋๋ฉด ๋๊ฐ๋ค ์
๋ฐ์ดํธ ํด์ผํ๋ ์ํฉ์์ ์ค์๋ก ํ๋๋ฅผ ๋บด๊ณ ์
๋ฐ์ดํธ ํ ์ ์๊ฒ๋๋ค.
- ๋ฐ๋ผ์ GOOD์์์ฒ๋ผ ์ค๋ณต๋ ์ ๋ณด๋ฅผ ์ ๊ฑฐํ๋ ๋ฐฉ์์ด ๋ฐ๋์งํ๋ค.
- Avoid deeply nested state
// BAD
export const initialTravelPlan = {
id: 0,
title: '(Root)',
childPlaces: [{
id: 1,
title: 'Earth',
childPlaces: [{
id: 2,
title: 'Africa',
childPlaces: [{
id: 3,
title: 'Botswana',
childPlaces: []
}, {
id: 4,
title: 'Egypt',
childPlaces: []
}, {
id: 5,
title: 'Kenya',
childPlaces: []
}, {
id: 6,
title: 'Madagascar',
childPlaces: []
}, {
id: 7,
title: 'Morocco',
childPlaces: []
}, {
id: 8,
title: 'Nigeria',
childPlaces: []
}, {
id: 9,
title: 'South Africa',
childPlaces: []
}]
}]
}]
};
// GOOD
export const initialTravelPlan = {
0: {
id: 0,
title: '(Root)',
childIds: [1],
},
1: {
id: 1,
title: 'Earth',
childIds: [2, 10, 19, 26, 34]
},
2: {
id: 2,
title: 'Africa',
childIds: [3, 4, 5, 6 , 7, 8, 9]
},
3: {
id: 3,
title: 'Botswana',
childIds: []
},
4: {
id: 4,
title: 'Egypt',
childIds: []
},
5: {
id: 5,
title: 'Kenya',
childIds: []
},
6: {
id: 6,
title: 'Madagascar',
childIds: []
},
7: {
id: 7,
title: 'Morocco',
childIds: []
},
8: {
id: 8,
title: 'Nigeria',
childIds: []
},
9: {
id: 9,
title: 'South Africa',
childIds: []
},
}
- ๋๋ฌด ๊น์ object๋ฅผ ์ํ์ ๋ฃ์ผ๋ฉด ์ํ๋ฅผ ์
๋ฐ์ดํธํ ๋ ์ฝ๋๊ฐ ์ฅํฉํด์ง ์ ์๋ค.
- ์ถ์ฒํ๋ ๋ฐฉ๋ฒ์ nested object๋ฅผ flatํ๊ฒ ๋ณ๊ฒฝํ์ฌ, ๊ฐ์ ์๊ธฐ ์์์ id๋ฅผ ๊ฐ์ง๊ณ ์๋ ์์ผ๋ก ๋ณ๊ฒฝํ ์ ์๋ค.