How do I get hot reloading to work when passing in functional components as props?

Viewed 22

App.tsx

import "./styles.css";
import { Parent } from "./components/parent";
import { Child } from "./components/child";

export default function App() {
  return <Parent child={Child} />;
}

Parent.tsx

import * as React from "react";

export const Parent: React.FC<{ child: React.FC }> = ({ child }) => {
  return (
    <div>
      Hot Reload Works
      {child({})}
    </div>
  );
};

Child.tsx

import * as React from "react";

export const Child: React.FC = () => {
  return <div>Hot Reload Does Not Work</div>;
};

How do I enable Hot Reload for my Child Functional Component when passing it as a parameter to the Parent? I've included the code sandbox that shows that hot reloading does not work in the child component.

Code Sandbox

1 Answers

Hot reloading allows you to see the changes that you have made in the code without reloading your entire app. As soon as you save your code, React tracks which files have changed since your last saved, and only reload those file for you.

Since you are passing the Child component as a prop function, it will only trigger changes in Child and will reload it. you are not changing the Parent component so it wont reload the changes made in the child({}) function.

The way to solve it is to pass the Child component as a children.

Parent.tsx

export const Parent: React.FC = ({ children }) => {
  return (
    <div>
      Hot Reload Works
      {children}
    </div>
  );
};

App.tsx

export default function App() {
  return (
    <Parent>
      <Child />
    </Parent>
  );
}
Related