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

164
Visualizações
React call functions on renderless component

I need to have a component for handling settings, this component (called Settings) stores state using useState(), for example the primary color.

I need to create a single instance of this component and make it available to every component in the app. Luckily, I already pass down a state dict to every component (I'm very unsure if this is the correct way to achieve that btw), so I can just include this Settings constant.

My problem is that I don't know how to create the component for this purpose, so that I can call its functions and pass it to children.

Here is roughly what my Settings component looks like:

const Settings = (props) => {
    const [primaryColor, setPrimaryColor] = useState("")
    const getColorTheme = (): string => {
        return primaryColor
    }
    const setColorTheme = (color: string): void => {
        setPrimaryColor(color)
    }
    return null
}


export default Settings

Then I would like to be able to do something like this somewhere else in the app:

const App = () => {
    const settings = <Settings />
    return (
        <div style={{ color: settings.getColorTheme() }}></div>
    )
}

Bear in mind that I'm completely new to react, so my approach is probably completely wrong.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a custom Higher Order Component(HOC) for this purpose, which is easier than creating a context(even thougn context is also a HOC). A HOC takes a component and returns a new component. You can send any data from your HOC to the received component.

const withSettings = (Component) => {
  const [settings, setSettings] = useState({})
  // ...
  // ...
  <Component {...props} settings={settings}/>
);

And you can use it like this:

const Component = ({ settings }) => {
   ...your settings UI
}
export default SettingsUI = withSettings(Component);

You can read more about HOCs in the official react documentation

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