在 React 發展的歷史裡,重用邏輯 (logic reuse) 一直是個難題。
Class component 時代,我們常用 HOC 或 Render Props 來抽象邏輯。
但這兩種方式都會遇到 Wrapper Hell 或 Nested Hell 的問題,程式碼可讀性差、維護不易。
隨著 Function component 與 Hooks 的出現,React 提供了更乾淨的方式來解決這些痛點:
那就是 Custom Hook。
use
開頭,並且在裡面使用其他 Hook(例如 useState
、useEffect
)。componentDidMount
、componentDidUpdate
、componentWillUnmount
。const withAuth = (WrappedComponent) =>
class extends React.Component {
state = { user: null };
componentDidMount() {
AuthAPI.check().then((u) => this.setState({ user: u }));
}
render() {
return <WrappedComponent {...this.props} user={this.state.user} />;
}
};
class Dashboard extends React.Component {
render() {
return <h1>Hello {this.props.user?.name}</h1>;
}
}
export default withAuth(Dashboard);
function useAuth() {
const [user, setUser] = React.useState(null);
React.useEffect(() => {
AuthAPI.check().then(setUser);
}, []);
return user;
}
function Dashboard() {
const user = useAuth();
return <h1>Hello {user?.name}</h1>;
}
Custom Hook 更直觀、可讀性更高。
在 Class component 時代,我們會用 HOC 或 Render Props 來重用邏輯,但這常導致 wrapper hell 或 nested hell,程式碼變得難讀。
Custom Hook 的出現解決了這個問題:它讓我們可以把邏輯抽象成 hook,再在不同 component 裡重用。這樣不但程式碼更簡潔,也讓 UI 結構更乾淨。
Back in the Class component era, we used HOCs or Render Props to reuse logic.
The problem was they often caused wrapper hell or nested hell, making the code hard to follow.
Custom Hooks solve this by letting us extract logic into hooks and reuse them across components. This keeps the code cleaner and the UI structure much simpler.