Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What happens if pass function component as state variable?

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>;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading