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.