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>;
    }

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

    Random posts

    Home
    Search
    Bookmark