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

105
Visualizações
Why can't I convert this to a custom React hook?

I've got a thin "service layer" in my React app that I use to push as much business logic into, and keep my components clean.

I've always used plain functions for this - passing in params and performing all the steps (reading/writing data, formatting stuff, etc.)

However, now that I've gotten a little more familiar w/ hooks, I'm wondering if it's possible to treat these functions as hooks, to make my life easier. For example, I'd like to be able to access the user object that's stored in context, whenever I need to, from this service layer.

Like so:

import { useContext } from "react";

import { AppContext } from "../component/global/app_context";

const Save = async link => {
    let { user } = useContext(AppContext); //bombs on this line!
    
    //...do stuff...
    
    return true;
};

export default Save;

I'd then call it like so:

const onEditSave = async link => {
    let updateRes = await Save(link);
    ...do other things...redirect, etc.
};

I keep getting the dreaded "Hooks can only be called inside of the body of a function component" error, so naturally I'm doing something wrong. I'm just failing to understand why this function can't be converted to a hook. How would I use it? Is this a stupid idea? If it is stupid, I'm fine w/ pulling the user and passing it into this function...it's just that I do this a lot and it seems tedious and pointless to put this in the components themselves.

Is there an easier way to access context values from a plain function, outside of those used to display React components?

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

0

You can certainly do what you're trying to do! It's just that you need to write a custom hook. You can call React hooks in function components and inside of other hooks.

A common pattern is to return functions from your custom hook that use values from other hooks.

In your case, I think your best best is to write a custom hook that gives you access to the AppContext you've created, plus additional "utilities".

Something like this.

// Inside component/global/app_context
import React, { useContext } from "react";

const AppContext = React.createContext()

const useAppContext = () => {
    const context = useContext(AppContext);
  
    function saveUser() {
        // ...do stuff with appContext.user ...
    }

    return {
      ...context,
      saveUser,
    }
}

export default useUserContext;

Then you can access it like:

const MyComponent = () => {
    const {user, saveUser} = useAppContext()
    //...rest of component
}

You can go very far with this pattern. So much power!

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