ReactTypeScript

IDEA: Using React Hook to make a componentWillUnmount alternative

The componentWillUnmount method will help us to reset the component state. But using React hooks, the official […]

広告ここから
広告ここまで

The componentWillUnmount method will help us to reset the component state.

class AnyComponent extends React.Component {
  componentWillUnmount() {
    this.props.resetTheTitle()
  }
  render() {
    return <h1>{this.props.title}</h1>
  }
}

But using React hooks, the official API is nothing.

IDEA: Create useComponentWillUnmount hook

My idea is to create a new custom hook instead of the componentWillUnmount.

import { useEffect, useCallback } from "react"

export const useComponentWillUnmount = (callback: Function, ...args: any[]) => {
    const cb = useCallback(() => {
        callback(...args)
    }, [callback, args])
    return useEffect(() => {
        return () => {
            cb()
        }
    }, [])
}

The hooks usage is here.

import { useComponentWIllUnmount } from './path/to/the/file';

type Props = {
  title: string,
  resetTheTitle: (postId: string) => void,
  postId: string
}
export default ({title, resetTheTitle, postId}: Props) => {
  useComponentWillUnmount(resetTheTitle, postId);
  return <h1>{title}</h1>;
}

Of course we can set multiple arguments into the function.

import { useComponentWIllUnmount } from './path/to/the/file';

type Tag = {
  Name: string;
  Value: string;
}
type Props = {
  title: string;
  resetTheTitle: (postId: string) => void;
  postId: number;
  author: string;
  tag: Tag
}

export default ({title, resetTheTitle, postId, author, tag}: Props) => {
  useComponentWillUnmount(resetTheTitle, postId, author, tag);
  return <h1>{title}</h1>;
}

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts