250x250
๋ฐ˜์‘ํ˜•
Notice
Recent Posts
Recent Comments
Link
ยซ   2024/07   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

BEAT A SHOTGUN

[REACT] useState ๋Œ€์‹  useMemo ๋ฅผ ์‚ฌ์šฉํ•ด๋ณด์ž ๋ณธ๋ฌธ

PROJECT

[REACT] useState ๋Œ€์‹  useMemo ๋ฅผ ์‚ฌ์šฉํ•ด๋ณด์ž

thovy 2022. 11. 23. 01:21
728x90
๋ฐ˜์‘ํ˜•
SMALL

์‹œ์ž‘ ๐Ÿ‘Š

์กฐํšŒ์ˆ˜ ์ฒดํฌ๋ฅผ ํ•  ๊ฑฐ๋‹ค.
์กฐํšŒ์ˆ˜๊ฐ€ ๋†’์€ top 10์„ ํ™”๋ฉด์— ์ถœ๋ ฅํ•  ๊ฑด๋ฐ
์กฐํšŒ์ˆ˜๊ฐ€ ๋ฐ”๋€Œ์—ˆ์„ ๋•Œ ๋ฆฌ์ŠคํŠธ๋„ ๋ฐ”๋€Œ์–ด์•ผ๊ฒ ์ง€?

๊ทธ๋ž˜์„œ ์ƒํƒœ๋ฅผ ์ฒดํฌํ•˜๋Š” useState ๋ฅผ ์‚ฌ์šฉํ•ด๋ดค๋‹ค.

useState

์กฐํšŒ๊ฐ€ ๋˜๋ฉด,
์กฐํšŒ๋˜๋Š” ํ•ญ๋ชฉ์„ props ๋กœ ๋ฐ›์•„์„œ, useState ๊ฐ€ ๋ณ€ํ™”๋ฅผ ๊ฐ์ง€ํ•˜๊ณ  ๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒˆ๋กœ ๋ Œ๋”๋งํ•  ์ƒ๊ฐ์ด์—ˆ๋‹ค.

// TopViews.tsx
TopViews(props:any){

  ...

const [topViewList, setTopViewList] = React.useState<Array<any>>();

useState(()=>(
    getTopView();
),[props])

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๊ณ„์†ํ•ด์„œ useState ๊ฐ€ ๋Œ์•„๊ฐ€๋”๋ผ.

๊ทธ๋ž˜์„œ ์–ธ์  ๊ฐ€ ๋ณธ ์  ์žˆ๋Š” useMemo ๋ฅผ ์‚ฌ์šฉํ•ด๋ดค๋‹ค.

useMemo

// TopViews.tsx
TopViews(props:any){

  ...

const [topViewList, setTopViewList] = React.useState<Array<any>>();

useMemo(()=> getTopView(), [props]);

์ด๋ ‡๊ฒŒ ํ•˜๋‹ˆ๊นŒ props ๊ฐ€ ๋ฐ”๋€” ๋•Œ๋งŒ ๋ฐ˜์‘ํ•˜๊ณ ,
StackOverFlow ์˜ ๊ณ ์ˆ˜๊ฐ€ ์ž˜ ์„ค๋ช…ํ•ด๋†“์€ ๊ฑธ ๋ณด๋‹ˆ
์•ž์œผ๋กœ useMemo ๋ฅผ ๋” ๋งŽ์ด ์‚ฌ์šฉํ•˜๊ฒŒ ๋  ๊ฒƒ ๊ฐ™๋‹ค.

์˜ˆ์ „์— ๋Œ“๊ธ€์„ useState ๋กœ ๊ณ„์† ๋ฐ›์€ ์ ์ด ์žˆ๋Š”๋ฐ, useMemo ๋ฅผ ์‚ฌ์šฉํ–ˆ์–ด์•ผํ–ˆ๋‚˜๋ณด๋‹ค.

์ฐธ๊ณ  : StackOverFlow

In terms of how often expensiveCalculation runs, the two have identical behavior, but the useEffect version is causing twice as much rendering which is bad for performance for other reasons.

Plus, the useMemo version is just cleaner and more readable, IMO. It doesn't introduce unnecessary mutable state and has fewer moving parts.

์ƒํ™ฉ์— ๋”ฐ๋ผ ๋‹ค๋ฅด๊ฒ ์ง€๋งŒ, ์–ธ์ œ ์จ์•ผํ•  ์ง€ ๋Œ€๊ฐ• ๊ฐ์ด ์˜จ๋‹ค.
์‰ฝ๋‹ค ์‰ฌ์›Œ.

๋

728x90
๋ฐ˜์‘ํ˜•
LIST
Comments