DEV Community

Discussion on: Composition vs Context in React

Collapse
lukeshiru profile image
LUKESHIRU

Account could be just a regular function, because is just returning a string:

const account = ({ status }) => (status ? "LogOut" : "LogIn");
Enter fullscreen mode Exit fullscreen mode

I don't think this is the best example for Composition vs. Context, but I see what you want to show. Basically is better to use children than context for scenarios like this, and I agree. Maybe making Account an actual component will make it more obvious. Maybe something like this:

import { useState } from "react";

const App = () => {
    const [connected, setConnected] = useState(false);

    return (
        <Header>
            <ConnectionButton connected={connected} />
        </Header>
    );
};

/** @type import("react").FC<JSX.IntrinsicElements["header"]> */
const Header = props => <header {...props} />;

/** @type import("react").FC<JSX.IntrinsicElements["button"] & { connected?: boolean }> */
const ConnectionButton = ({ children, connected, ...props }) => (
    <button {...props}>{children ?? (connected ? "Log Out" : "Log In")}</button>
);
Enter fullscreen mode Exit fullscreen mode

Cheers!