์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
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 |
- axios
- Troubleshooting
- EC2
- nodejs
- python
- MongoDB
- MUI
- webhook
- RDS
- Express
- linux
- error
- springboot
- Java
- macbook
- ngrok
- AWS EC2
- AWS
- github
- TypeScript
- docker
- Jenkins
- js
- Spring
- fastapi
- deploy
- React
- javascript
- Github Actions
- 500
- Today
- Total
BEAT A SHOTGUN
[REACT] useState ๋์ useMemo ๋ฅผ ์ฌ์ฉํด๋ณด์ ๋ณธ๋ฌธ
์์ ๐
์กฐํ์ ์ฒดํฌ๋ฅผ ํ ๊ฑฐ๋ค.
์กฐํ์๊ฐ ๋์ 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.
์ํฉ์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ์ง๋ง, ์ธ์ ์จ์ผํ ์ง ๋๊ฐ ๊ฐ์ด ์จ๋ค.
์ฝ๋ค ์ฌ์.