React
custom hook 따라 만들기
daehwan2
2022. 10. 24. 22:24
매일 듣고 기록해보자 ( 계속 추가 예정 ) 🔥🔥
All Courses – 노마드 코더 Nomad Coders
초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!
nomadcoders.co
1. useInput
export const useInput = (initialValue, validator) => {
const [value, setValue] = useState(initialValue);
const onChange = (e) => {
const {
target: { value }
} = e;
let willUpdate = true;
if (typeof validator === "function") {
willUpdate = validator(value);
}
if (willUpdate) {
setValue(value);
}
};
return { value, onChange };
};
2. useTabs
export const useTabs = (initialTab, allTabs) => {
if (!allTabs || !Array.isArray(allTabs)) return;
const [currentIndex, setCurrentIndex] = useState(initialTab);
const changeItem = (selectIndex) => setCurrentIndex(selectIndex);
return {
currentItem: allTabs[currentIndex],
changeItem: setCurrentIndex
};
};
3. useTitle
활용법이 너무 좋은것같다... 😦
setState 함수를 리턴해주고 업데이트시마다 useEffect로 .. 업데이트..
export const useTitle = (initialTitle) => {
const [title, setTitle] = useState(initialTitle);
const updateTitle = () => {
const htmlTitle = document.querySelector("title");
htmlTitle.innerText = title;
};
useEffect(updateTitle, [title]);
return setTitle;
};
반응형