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

138
Visualizações
Reactjs separation of UI and business logic

I am new to react and I find it sore in the eyes to look at the component flooded with lots of functions and variable initializations together with the UI. Is it possible to separate them?

Instead of the default setup, like below. How do I separate the business logic into another file?

function MyComponent() {
    const [data, setData] = useState('');
    const someFunc = () => {
        //do something.
    };
    ... some 100-liner initializations

   return ( 
       ...
   )
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

A common approach that I use myself is to separate the business logic into its own file myComponentHelper.js

This will also make it easier to test the function because it will not be able to use and change the react state without having it passed in as arguments and returning the changes.

myComponent/
  myComponent.jsx
  myComponentHelper.js
  myComponentTest.js
// myComponent.js

import { someFunc } from './myComponentHelper';

function MyComponent() {
    const [data, setData] = useState('');
    
    const x = someFunc(data);

    return ( 
        ...
    )
}
// myComponentHelper.js

export const someFunc = (data) => {
    //do something.
    return something;
}
// myComponentTest.js

import { someFunc } from './myComponentHelper';

test("someFunc - When data is this - Should return this", () => {
    const data = {...};
    const result = someFunc(data);
    expect(result).toEqual("correct business data");
});
over 4 years ago · Santiago Trujillo Relatório

0

Separating business logic into other files can be done in various different ways.

  1. Create a helperFile.js that has logic or basically the functions required by the corresponding file.
  2. Creating Custom Hooks. More on that can be found here in the official docs or in this playlist (refer the videos at the very end)
  3. Global State mangement way - where contextAPI or Redux is used to seperate out state and business logic
over 4 years ago · Santiago Trujillo 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