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 (
...
)
}
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");
});
Separating business logic into other files can be done in various different ways.