The meaning of life is to explore the world

some tips of changing a class component to a functional component

Posted on By Jason Liu

There are some reasons we may want to convert a class component to a functional component.
E.g. Hooks are only available in functional components like const queryString = useLocation().search;
This can be quite useful in React Router.

Lifecycle methods from class components can be converted to useEffect hooks.

  • useEffect(() => { ... }) will run after every render
  • useEffect(() => { ... }, []) will run only once after component mounts
  • useEffect(() => { ... }, [dep1, dep2]) will run only when one of the dependencies changes
  • useEffect(() => { return () => { ... }; }, [deps]) will be triggered during clean up phase. i.e. triggered when:
    • On component unmount (if the array is empty).
    • On dependency change, it cleans up the previous effect before re-running the new effect.