what is custom hook and how to use it (1)

hyeok·2022년 12월 31일
1
post-thumbnail

Custom hook looks like a function. However custom hook have its own variable keeps its own state. It is very useful in developing.

For example, we can use custom hook to check the view size and does view size fit with mobile view or not.

const useIsMobile = ()=> {
	const [isMobile, setIsmobile] = useState(false);
    
    useEffect(()=> {
    	// check window size 
        const handleResize = ()=>{
        	if(window.width< 900){
				setIsMobile(true)		
			}else{
            	setIsMobile(false)
            }
        }
     window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);   
    },[window])

	return [isMobile]
}

By using this hook, we can catch the window size changes and get the boolean value that shows that window is in mobile size or not.

In this hook we got a state that separated from the main logic. We can use the state when we want.

We should focus on how hook got his own state. It is attributed from the one of JS features, Closer. I will talk about it in next blog.

profile
내가 만든 소프트웨어가 사람들을 즐겁게 할 수 있기 바라는 개발자

0개의 댓글