Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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>;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!