Closures in React

--- title: 'Closures in React' author: 'Hun Im' date: 2024-09-11T13:53:35+09:00 category: ['POSTS'] tags: ['Javascript', 'React'] og_image: "/images/gamer.png" keywords: ['Javascript', 'React'] --- Closures are a fundamental concept in JavaScript. It's a concept that is often asked about in technical interviews, and I remember memorizing it while preparing for my own technical interviews. However, I didn't quite understand how closures are used in practice, and I often pondered how to apply them effectively. This time, I want to study the concept of closures in more depth. **Problem** *When passing a function as a parameter to `customHook`, let’s observe how the `state` value inside the function is output when the `useCustom` component is unmounted.* ```jsx import useCustom from './hooks/useCustom' import { useState } from 'react' export default function Home() { const [state, setState] = useState(0) useCustom(() => console.log('inner func state:', state)) return ( <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> <div>{state}</div> <button onClick={() => setState(state + 1)}>+</button> </div> ) } ``` ```jsx import React, { useEffect } from 'react' const useCustom = (func: Function, state: any) => { console.log('params state:', state) useEffect(() => { return () => func() }, []) return <div>useCustom</div> } export default useCustom ``` **Code Explanation** 1. On the initial render, the `state` is set to 0. 2. The `console.log` inside `useCustom` outputs the value of `state`, which is the initial value of 0. 3. At this point, the `func` function passed to `useCustom` also retains the state of 0 due to closures. When the `useCustom` component is unmounted, this function executes, but the `state` remains at 0. 4. Since the dependency array is empty, the `useEffect` runs only once, and it does not re-execute even if the `state` changes. 5. If you want to use the latest `state` value, you need to add `state` to the dependency array of `useEffect`. Otherwise, due to closures, it will reference the previous state.
Β 
--- title: 'λ¦¬μ•‘νŠΈμ—μ„œμ˜ ν΄λ‘œμ €' author: 'μž„ν›ˆ' date: 2024-09-11T13:53:35+09:00 category: ['POSTS'] tags: ['Javascript', 'React'] og_image: "/images/gamer.png" keywords: ['Javascript', 'React'] --- ν΄λ‘œμ €λŠ” μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œ 기본이 λ˜λŠ” μ•„μ£Ό μ€‘μš”ν•œ κ°œλ…μ΄λ‹€. 기술 λ©΄μ ‘μ—μ„œ 1μˆœμœ„λ‘œ 자주 λ¬Όμ–΄λ³΄λŠ” κ°œλ…μ΄κΈ° λ•Œλ¬Έμ—, λ‚˜λ„ 기술 면접을 μ€€λΉ„ν•˜λ©° μ™Έμ› λ˜ 기얡이 λ‚œλ‹€. ν•˜μ§€λ§Œ, μ‹€λ¬΄μ—μ„œ ν΄λ‘œμ €κ°€ μ–΄λ–»κ²Œ μ“°μ΄λŠ”μ§€ 잘 μ΄ν•΄ν•˜μ§€ λͺ»ν–ˆκ³ , 이λ₯Ό μ‹€μ œλ‘œ μ–΄λ–»κ²Œ μ‘μš©ν•΄μ•Ό ν• μ§€ κ³ λ―Όν•˜λ˜ μ‹œκΈ°κ°€ μžˆμ—ˆλ‹€. μ΄λ²ˆμ— ν΄λ‘œμ € κ°œλ…μ„ 더 심도 있게 곡뢀해보렀 ν•œλ‹€. **문제** *`customHook`에 ν•¨μˆ˜λ₯Ό νŒŒλΌλ―Έν„°λ‘œ λ„˜κ²¨μ€„ λ•Œ, `useCustom` μ»΄ν¬λ„ŒνŠΈκ°€ μ–Έλ§ˆμš΄νŠΈλ˜λŠ” μƒν™©μ—μ„œ ν•΄λ‹Ή ν•¨μˆ˜κ°€ 싀행될 λ•Œ, ν•¨μˆ˜ λ‚΄λΆ€μ˜ `state` 값이 μ–΄λ–»κ²Œ 좜λ ₯λ˜λŠ”μ§€ μ‚΄νŽ΄λ³΄μž.* ```jsx import useCustom from './hooks/useCustom' import { useState } from 'react' export default function Home() { const [state, setState] = useState(0) useCustom(() => console.log('inner func state:', state)) return ( <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> <div>{state}</div> <button onClick={() => setState(state + 1)}>+</button> </div> ) } ``` ```jsx import React, { useEffect } from 'react' const useCustom = (func: Function, state: any) => { console.log('params state:', state) useEffect(() => { return () => func() }, []) return <div>useCustom</div> } export default useCustom ``` **μ½”λ“œ μ„€λͺ…** 1. 초기 λ Œλ”λ§ μ‹œ `state`λŠ” 0으둜 μ„€μ •λœλ‹€. 2. `useCustom` ν›… λ‚΄λΆ€μ˜ `console.log`에 좜λ ₯λ˜λŠ” `state` 값은 초기 값인 0이닀. 3. μ΄λ•Œ `useCustom`μ—μ„œ λ„˜κ²¨μ€€ `func` ν•¨μˆ˜λ„ ν΄λ‘œμ €λ‘œ 인해 `state`κ°€ 0인 μƒνƒœλ₯Ό κΈ°μ–΅ν•˜κ²Œ λœλ‹€. 이후 `useCustom` μ»΄ν¬λ„ŒνŠΈκ°€ μ–Έλ§ˆμš΄νŠΈλ  λ•Œ ν•΄λ‹Ή ν•¨μˆ˜κ°€ μ‹€ν–‰λ˜μ§€λ§Œ, κ·Έλ•Œμ˜ stateλŠ” 0으둜 남아 μžˆλ‹€. 4. μ˜μ‘΄μ„± 배열이 빈 배열이기 λ•Œλ¬Έμ— `useEffect`λŠ” ν•œ 번만 μ‹€ν–‰λ˜λ©°, `state`κ°€ λ°”λ€Œλ”λΌλ„ μž¬μ‹€ν–‰λ˜μ§€ μ•ŠλŠ”λ‹€. 5. λ§Œμ•½ μ΅œμ‹  `state` 값을 μ‚¬μš©ν•˜κ³  μ‹Άλ‹€λ©΄, `useEffect`의 μ˜μ‘΄μ„± 배열에 `state`λ₯Ό μΆ”κ°€ν•΄ μ£Όμ–΄μ•Ό ν•œλ‹€. κ·Έλ ‡μ§€ μ•ŠμœΌλ©΄ ν΄λ‘œμ €λ‘œ 인해 이전 μƒνƒœλ₯Ό μ°Έμ‘°ν•˜κ²Œ λœλ‹€.