What happens if pass function component as state variable?

Advertisements

What happens if I pass function component as state variable?

For example, would the below technically work? I tried it and it doesn’t seem to work. I get the error props.children isn’t a function. Any idea whether this would work?

const App = () => {
    [functionComponent, setFunctionComponent] = useState((name) => <div>Hi, {name}</div>)
    
    return <SomeContainerComponent>{functionComponent}</SomeContainerComponent>

}

const SomeContainerComponent = ({ children }) => {
   return <div>{children({name: "John"})}</div>;
}

>Solution :

When you pass a function (whether a function that returns JSX or not) to useState, you’re telling React to use lazy initialization – to call the function to compute the value for the initial state, rather than to set the state to be the function you passed in.

For what you want, you’d need to pass a function that returns a function, and also capitalize the state, since it’s a component.

const App = () => {
    const [FunctionComponent, setFunctionComponent] = React.useState(() => () => <div>Hello, World!</div>);
    return <FunctionComponent />;
};

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

Leave a ReplyCancel reply