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

213
Visualizações
How to make a reusable function that calls setUserContext? React Hooks useContext

So I have 4 components that are all doing the same thing inside an onClick handler.

I have to define this code in every single one of them.

The reason I don't know how to make this reusable is that you cannot call setUserContext inside a regular non-react utility function. I tried creating a hook but you cannot use Hooks as callbacks inside onClick.

What are my options here?

  const { userContext, setUserContext } = useContext(UserContext);

  // this goes inside onClick and is defined in like 4 components (too much repetition)
  const favoriteItem = (e) => {
    e.stopPropagation();
    e.preventDefault();
    setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
  }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can create a custom hook.

const useCustomHook = () => {


const { userContext, setUserContext } = useContext(UserContext);

  const favoriteItem = (event, game) => {
    e.stopPropagation();
    e.preventDefault();
    setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
  }

return { favoriteItem } 
} 


export default useCustomHook;

Your component can do this.

... 
const { favoriteItem } = useCustomHook() 

return (
<Element onClick={(event) => favoriteItem(event, game)} /> 
) 
... 
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