Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda