React: Component VS Element as Prop

const A = ({ component }: { component: () => JSX.Element }) => {
const Component = component;
return <Component />;
};

const B = () => {
return <div>as component</div>;
};

export default function App() {
return <A component={B} />;
}
import { useState } from "react";

const A = ({ component }: { component: () => JSX.Element }) => {
const Component = component;
return <Component />;
};

const B = ({ count }: { count: number }) => {
return <div>{`as component with state:${count}`}</div>;
};

export default function App() {
const [count, setCount] = useState(0);
return (
<>
<A component={() => <B count={count} />} />
<button
onClick={() => {
setCount((count) => count + 1);
}}
>
increase the count
</button>
</>
);
}
import { useEffect, useState } from "react";

const A = ({ component }: { component: () => JSX.Element }) => {
const Component = component;
return <Component />;
};

const B = ({ count }: { count: number }) => {
useEffect(() => {
console.log("mounted");
return () => {
console.log("unmounted");
};
}, []);
return <div>{`as component with state:${count}`}</div>;
};

export default function App() {
const [count, setCount] = useState(0);
return (
<>
<A component={() => <B count={count} />} />
<button
onClick={() => {
setCount((count) => count + 1);
}}
>
increase the count
</button>
</>
);
}
import { useEffect, useState } from "react";

const A = ({ element }: { element: JSX.Element }) => {
return element;
};

const B = ({ count }: { count: number }) => {
useEffect(() => {
console.log("mounted");
return () => {
console.log("unmounted");
};
}, []);
return <div>{`as component with state:${count}`}</div>;
};

export default function App() {
const [count, setCount] = useState(0);
return (
<>
<A element={<B count={count} />} />
<button
onClick={() => {
setCount((count) => count + 1);
}}
>
increase the count
</button>
</>
);
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store