import React, { useState, useEffect } from "react";
export default function App() {
const [word, setWord] = useState();
const [title, setTitle] = useState('init title');
useEffect(() => {
document.title = title;
}, [title])
return (
<div className="App">
<h1>Title Changer</h1>
<h2>변경된 타이틀은 {title}</h2>
<input placeholder="input here" onChange={(e) => setWord(e.target.value)}/>
<button onClick={() => setTitle(word)}>Change</button>
</div>
);
}
import React, { useState, useEffect } from "react";
const useTitle = init => {
const [word, setWord] = useState();
const [title, setTitle] = useState(init);
const onChange = e => {
const {
target: { value }
} = e;
if (value) {
setWord(value);
}
};
const onClick = () => {
setTitle(word);
}
useEffect(() => {
document.title = title;
}, [title]);
return { title, onChange, onClick };
};
export default function App() {
const title = useTitle("init title");
return (
<div className="App">
<h1>Title Changer</h1>
<h2>변경된 타이틀은 {title.title}</h2>
<input placeholder="input here" onChange={title.onChange}/>
<button onClick={title.onClick}>Change</button>
</div>
);
}
오히려 Custom hook의 코드량이 많아보일 수 있겠지만, 이를 모듈로 하여 필요한 다른 곳에서도 재사용이 가능하다는 장점이 있다.
그럴 때는 모듈을 불러오고 호출하는 것 만으로 코드량을 줄일 수 있다.
import useTitle from 'path';
const title = useTitle("init title");