Framework/React

[React] React Hook "useSelector" cannot be called inside a callback ์—๋Ÿฌ ๋ฐ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

yuri lee 2023. 9. 18. 22:03
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. react hook useSelector ๋ฅผ ์‚ฌ์šฉํ•˜๋˜ ๋„์ค‘ ์•„๋ž˜์˜ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. 
 

React Hook "useSelector" cannot be called inside a callback

 

function YourComponent() {
      useEffect(() => {
        useSelector((state: RootState) => state.code[SOME_DATA])
      }, [])
}

 

Why?

react hook์„ ์‚ฌ์šฉํ•  ๋•Œ๋Š” ์ค‘์š”ํ•œ 2๊ฐ€์ง€ ๊ทœ์น™์ด ์žˆ์Šต๋‹ˆ๋‹ค. 

 

1๏ธโƒฃ Only Call Hooks at the Top Level

๋ฃจํ”„ ์กฐ๊ฑด ๋˜๋Š” ์ค‘์ฒฉ๋œ ํ•จ์ˆ˜ ๋‚ด์—์„œ Hooks๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ํ•ญ์ƒ React ํ•จ์ˆ˜์˜ Top Level์—์„œ Hooks๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ด ๊ทœ์น™์„ ๋”ฐ๋ฅด๋ฉด Component๊ฐ€ ๋ Œ๋”๋ง๋  ๋•Œ๋งˆ๋‹ค  Hoooks์ด ๋™์ผํ•œ ์ˆœ์„œ๋กœ ํ˜ธ์ถœ๋ฉ๋‹ˆ๋‹ค. 
 

2๏ธโƒฃ Only Call Hooks from React Functions

์ผ๋ฐ˜ JavaScript Function์—์„œ Hooks๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. 

 

My Case

์ œ ๊ฒฝ์šฐ ํ•ด๋‹น ๊ทœ์น™์— ์œ„๋ฐ˜ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์Œ์˜ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋˜ ๊ฒƒ์ž…๋‹ˆ๋‹ค. 

 

How to solve the problem

useSelector๋ฅผ ์ง์ ‘ useEffect ๋ฐ–์—์„œ ํ˜ธ์ถœํ•˜๊ณ  ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”์ถœํ•œ ๋‹ค์Œ์— useEffect ๋‚ด๋ถ€์—์„œ ์‚ฌ์šฉํ•˜์—ฌ ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•˜์˜€์Šต๋‹ˆ๋‹ค.  useSelector๊ฐ€ useEffect ๋‚ด๋ถ€์—์„œ ์ง์ ‘ ํ˜ธ์ถœ๋˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, someData๋ผ๋Š” ๋ณ€์ˆ˜์— ์ €์žฅ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”์ถœํ•œ ํ›„ useEffect ๋‚ด์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ React Hook ๊ทœ์น™์„ ์ค€์ˆ˜ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค :)

function YourComponent() {
  const someData = useSelector((state: RootState) => state.code[SOME_DATA]);

  useEffect(() => {
    // ์˜ˆ: console.log(someData);
  }, [someData]);

  // ๋‚˜๋จธ์ง€ ์ปดํฌ๋„ŒํŠธ ์ฝ”๋“œ...
}

 


https://legacy.reactjs.org/docs/hooks-rules.html

๋ฐ˜์‘ํ˜•