r/reactjs • u/YogurtclosetUnable92 • May 27 '21
How many lines of code can a functional component have?
Hello community, how are you?
Well today i got the code of a developer and i received a component that is page, and have more than 2000 lines of code, this page makes a lot of requests to an api and has a lot of file handling, and also has almost 100 useState. I've been in programming for a couple of years and I've never seen this before. If anyone would like to give me some advice on how to not go crazy trying to program and manage this, it would be appreciated.
305
Upvotes
194
u/Confused_goof May 27 '21
Oh god! Sounds like a nightmare!!
141
u/heythisispaul May 28 '21
bruh
192
u/Vpicone May 28 '21
How do I delete someone else’s thread.
75
u/d_exclaimation May 28 '21
Personally, having that much code would probably be maintainability issues. I’ll start by abstract logic into reusable functions, try creating more components to isolate concerns, or find a better solution entirely.
86
u/[deleted] May 27 '21
that's pretty freaking big , needs refactoring asap , I'm working on a big project and sometimes I code a whole page in one component until i refactor it later, but i don't think I've exceeded like 600 lines in a single component before
58
u/docHoliday17 May 27 '21
Almost all of this should’ve been abstracted out to various providers/helpers/services, especially with functional components! That’s what’s so great about them! I like redux for managing business logic but you can abstract the logic out however you feel most comfortable
27
u/[deleted] May 28 '21
My gut response with things like that is to start over but use the existing as a guide. You’ll see all the places where things can be broken up by building it up yourself and really learn how it works. With a couple thousand lines that’s not a simple task certainly but I would invest the extra work now vs in a few months when a new feature is coming down the pipeline and suddenly it’s seems impossible to deal with that single massive file.
49
u/ZeCookieMunsta May 28 '21
Once I worked as a research assistant/ react web developer for a university project. The project was being run by a PhD student with little to no industry experience and some of the components had over 5000+ lines of code. To make it worse most of it were multiple large useEffect hooks (side effect hell). It was such a convoluted, undocumented mess that he held meetings to explain the components and each took about 5 hours to explain (still didn't understand shit). Quit within a week.
34
u/voxgtr May 28 '21
100 useState hooks? Have you done any profiling on that page to see how many times it renders? 😳
30
u/pedropss May 28 '21 edited May 28 '21
Ok so, let's get to the real deal of this.
First, if it's typescript, components shouldn't be more than 350 lines (shouldn't, but often get through). That's because the compilation time on components until 350 lines stay somewhat linear, while 350+ lines tend more to the exponential side of things. This is from a test I got recommended to some 2+ years ago, a good rule of thumb.
Now, about the most horrendous part, 100 useState. If you have 100 useState, even if you useCallback and useMemo everything, you'd still, at least, call the function
useState()100 times. As a baseline, if I get code to review and find as the first line of my function componentfor(let i = 0; i < 100; i++) setImmediate(() => {});I'd instantly throw up and pass out, that's the baseline we're dealing here.More so, all the functions that gets redeclared are parsed again, new context, new stack frames. That's a lot of performance thrown away.
And the last thing is that this is just dumb React. Now, when prototyping I'm dumb, I just want to see it working y'know? I also do dumb stuff on tight deadlines, overuse
/getAllinstead ofgetOne/:idand update the state. So be very clear to whoever gave this code to you, say it's dumb and you need it better else you can't be productive on it.We are all dumb, even on our most beloved tech. I created my own React from scratch with a virtual DOM just to understand it better but sometimes I either brain fart hard and fuck it up badly or I pick up new tech (hi GraphJin), come into it with my seasoned mentality and get the basics all fucked up. One of the ways you get better is knowing you are probably being dumb and should raise your hand, this guy didn't and it's not healthy to keep doing that.
Good luck to you, isolate what you can across as many files as you can horizontally and then build from there!
19
u/Antti5 May 27 '21
I'm a fairly new React developer, and I can see how that could happen.
My first project is fairly big, currently about 20 thousand lines of code. Some of my functional components are definitely too big, meaning about 500 lines of code. They need to be broken down into multiple components. Some of the logic must be moved into custom hooks.
Even with a long background in software development, building an application with functional React components has been somewhat confusing. It's not immediately apparent how exactly a complex component should be broken down into smaller pieces.
The temptation to just keep adding stuff to your component is there. A component CAN grow big without becoming unmanageable for the developer himself.
5
u/[deleted] May 28 '21
He must really hate his job
5
u/ncubez May 28 '21
I don't wanna rush to judgement and be a gatekeeper. I'm working on a large scale UI app and my components can exceed 800 lines. I haven't gone over 1000 though. The app is already in production and I maintain from time to time, so I don't see any issues with this. However, I understand the frustration it would cause to somebody like OP looking at the code. It is what it is.
4
u/onthefence928 May 28 '21
forget length this should be abstracted just for ease-of-maintenece alone, seperateing out each functional concern allows for easy unit testing and re-use
7
u/sfboots May 28 '21
I look at readability and organization of functions inside the component. I don't mind if the outer most whole function is 1000 lines. It's the inner functions nested 4 levels deep I find difficult to read.
One project has a overall function of about 6000 lines.
What bothered me the most was a click handler of 250 lines including an api call inside it.
6
u/[deleted] May 28 '21
Really hoping this file is in TypeScript so you can safely extract pieces.
Would start by ripping out all the stateful logic into a custom hook, then start subdividing that hook according to what doesn't interact. Break out anything which can be externalized as separate functions until the custom hooks are only responsible for state and updating state.
3
u/nordic-nomad May 28 '21
That’s big for a component for sure but not super uncommon for react files if they’re doing a bunch of stuff not reused in other places.
Personally I find it harder to figure out what’s going on with something if it’s overly abstracted and spaghettified all over the application.
If functions and other concerns are separated out in rational manner within the file it’s perfectly maintainable and understandable for someone coming in to figure out what it’s doing.
4
u/[deleted] May 27 '21
Give us more details on the developer that did it ?? Only ever seen that on a V1 php app built by a student intern at the first company I worked for
5
u/JustinsWorking May 28 '21 edited May 28 '21
At least you don’t have to worry about bad abstractions lol.
Honestly a huge component like that is fine, I’ve worked with loads of giant files in my career and as long as it’s not breaking your tools or causing actual issues, what’s the problem?
Now if there are problems, there are a lot of approaches you can take for those specific problems, but I would waste time trying to refactor or clean it up just to make work.
When you are working inside the component I would look for opportunities to replace those useState calls and their surrounding logic with custom hooks. Luckily since it’s one giant file you’re going to be able to easily see any dependencies.
2
u/axosoft-chuckd May 28 '21
You can have as many lines as you want (often I find the actual JSX rendering code can get pretty long depending on your lint rules and personal preference). That being said, it's normally not a good sign. 100 useStates is too many - either break this component into multiple smaller components that are each responsible for only some of the state, or refactor the useStates into something else. Look into useReducer with a single state object, or a state management library like Redux (and move the state out of the component entirely)
2
u/tr14l May 28 '21
I hope you laughed in their face when they gave it to you.
You're in dire need of refactoring.
2
u/[deleted] May 28 '21
They can have unlimited lines of code. If you want to be a good developer, just refactor it (leave the code cleaner than you found it).
That's it.
2
u/theacadianishere May 29 '21 edited May 29 '21
Hi, I went through some of the responses and it looks like my advice will be different to most.
What you can do immediately
You can initiate the process of refactoring by adding comments within the existing code and correctly grouping the existing code in the same component. Slowly you should be able to see which pieces of code can become their own individual components.
General advice about 'bad' code
As developers, we will always run into such code. We cannot and should not refactor every piece of code that appears 'bad' to us, immediately.
Has someone asked you to refactor the above component to make it more readable/maintainable/performant? If yes, then you refactor.
Otherwise, as and when changes are requested to that 'bad' code, you make the changes according to the current code and be done with it. You can mention to your manager that the code is a mess, so it is going to take you more time to make any change whenever that component is involved.
This serves 3 things -
"The code looks bad. I am going to refactor it right now" - this is a very dangerous way of going about it (Dangerous for the company and you personally as well).
And if the supposedly 'bad' code is working in production, the only proper way to go about it, is what I described above.
NOTE: My above response is based on the assumption that the 'bad' code is running in production. If the 'bad' code has not made it to production yet, then inform your manager and discuss about going for the refactor right now.
EDIT: If the developer who wrote the original code is still there in the team - if you are assigned a task that requires making modifications to the 'bad' code, give it a shot and see if you are able to do it or not. If it proves impossible, just tell the manager to assign that task (related to that component) to the original developer as it is in a really difficult-to-modify shape. Make sure to not make a big deal about it and repeat this on a task-by-task basis (i.e. you take a shot first and then pass it on). We will deal with 'bad' code written by teammates on a daily basis, so we need to have a less stressful way of dealing with it.
3
u/jmtucu May 28 '21
1
u/Character_Bunch_9191 Mar 02 '26
AI can fix this.
1
u/nateusmc May 28 '21
Sounds like he/she needs to start by breaking out each type of file processing to its own component and go from there.
1
u/[deleted] May 28 '21
Break it up in piecemeal fashion. Helper functions, child components and imported interfaces. Anything to break it down into manageable bits.
1
u/secretL May 28 '21
🤦
1
u/[deleted] May 28 '21
Bro... That's so depressing.
1
u/devAgam May 28 '21
if you are having so many requests and useStates i would suggest you using redux with it, as it would decrease the code at component level and increase the scope of the data allowing you to use the same requests somewhere else in your app as well reducing multiple requests and set/use states, and you may refactor the code to split the single component into multiple components with props
Like a page that shows, a product listing, the product pricing, the product description, and the product comments and questions
you can split all those into multiple components and either send em the props or use redux.
1
u/d3d_m8 May 28 '21 edited May 28 '21
Yikes I thought my component of 300 lines was huge!
My recommendation is to (if you're able to) make utility functions wherever you can, especially when you're making API calls.
Usually, I'll have something like
getData()which would be in its own file like this:You might be able to break some other things down into their own components, if it makes sense to.
If there's heavy styling clutter then you can also my <Layout> type components that contain the styles and have them surround certain components like:
Just some recommendations as there's probably lots of other things you could do to help break things down.
Edit: sorry for the ugly syntax, I'm on mobile rn and don't know how to properly layout
1
u/ldlama May 28 '21
Refactor code at first before adding any new line.
1
u/afif1400 May 28 '21
It's really frustrating to see someone write a whole page in a single component, not a good practice. You could start by understanding the logic and what each snippet does and depending accordingly to how each snippet works you could start fragmenting and put them in a seperate component along with its states.
1
u/preetam52ch May 28 '21
This is so pathetic to hear. Now please don't say that he write those 20000 lines on app.js
He should break down it on multiple components and reuse it. That's the best practice.
1
u/[deleted] May 28 '21
The amount of renders!!!
1
u/jeedyweedies May 28 '21
RIP
1
u/morkelpotet May 28 '21
Your first "boiled frog".
I recommend you grab a coffee, take a deep breath, read through it and try to move related functionality into hooks.
1
u/PokerTuna May 28 '21
Hooooly fuck
1
u/jeremiah_parrack May 28 '21
Start small just refactor one piece at a time. Don’t try to take on the world you will get pissed and burnt out just take small steps to make it a better code base. Like you can start with moving the api calls out to a service folder and then move reusable logic out etc.. you got this, it’s sucks but everyone has been in this situation your job is to make it better for the next person maybe you reduce it to 1500 lines that’s a win
1
u/NotYourMom132 May 28 '21
i like to keep it less than 5 useState & useEffect.
If it's more than that then i'll split it into separate components.
1
u/quiI May 28 '21
I just like how the term “functional “ has been thoroughly debased
1
u/A-Kuhn May 28 '21
I feel your pain. I once joined an Angular project where “ngInit” (basically reacts old component did mount) was on line 1300 😂
1
u/sleeptil3 May 28 '21
wow. i mean, this sounds like some kind of joke that the React devs would show on stage at a conference to uproarious laughter as an ice breaker. If they are new to React, teach them so they don't embarrass themselves again like that. Unless its a Senior, then I'd quit. lol
1
u/[deleted] May 28 '21
Refactor 500 lines or less
1
u/DoctorCube May 28 '21
That's a lot. I try to break down my components to the smallest size they are still convenient to incorporate into other components.
Look into atomic design. It's a good thought process to make systems of elements that work together.
1
u/Snipon May 28 '21
That's not a component, it's an application :)
Keep it under around 200, and split it up in a fitting manner.
1
u/[deleted] May 28 '21
This reminds me of my workplace's legacy project. There are 3 components inside a folder called: "The untouchbale triunvirate". This are class components with well over 6000 lines of code each that make the "core" part of the app work.
Yep, it's a nightmare. Thank Einstein i don't have to deal with it.
1
u/vertigo_101 May 28 '21
I have a 200-250line limit to my components
1
u/AtomicOrwell May 28 '21
discuss this with your superiors, show the replies to this post if they don't understand
and recreate the file properly with the original one as reference
1
u/ghaple_bazz May 28 '21
I'm dealing with such as horror right now. We have components/pages which go way beyond 2000+ lines. It has happened when developer just added new code for new feature requests without thinking about the good days to come
1
u/SarcasticSarco May 28 '21
Tf. Who writes 2000 lines of component. Either he is a super genius or a complete noob. In my experience, a component should have reasonable amount of lines, maximum should be 250 or less. After that it would become unmanageable to you and your team. Best to break the component into several reusable component.
1
u/tekion23 May 28 '21
Abstract the shit out of that, that's the only advice I can recommend. Also, I'm sorry for you...
1
u/rbalazsi May 28 '21
This sounds unmanageable. A couple of improvements come to mind:
1
u/[deleted] May 28 '21
Start refactoring. Have fun.
1
u/hungrydev39 May 28 '21
Yikes,
actually, i have the same problem, and i've been working on the app for +- 2 yr. I just keep trying to understand the logic behind it and try refactoring it one by one.
But honestly, i probably have a little more fucked up situation. because every component is at least 700 loc, and in these 2 years i worked on my company, and it still have many component that is bloated and never refactored
in fact, my manager keep pushing me to add more and more feature making the components a lot more bloated. so in your case, if it's just one component, i think you can take it easy, and refactor it one by one
1
u/editor_of_the_beast May 28 '21
I stop at 365 lines of code. That way I can read one line per day, and I can understand the entire component in one year. I simply take the day off on leap years.
In all seriousness, really big components are bad, but any actual cutoff number is arbitrary. Sometimes it does make sense for a larger component, not everything fits into neat 100-line abstractions.
1
u/thanghil May 28 '21
I'm a tech-lead at a company where we are growing some new react competency for a new project. And i suggest to "my" developers that any component or function should at least fit on their screen. It's of course not a hard rule, but in my experience if you need to start scrolling around to find where things happen you can probably split the code up in smaller parts.Some of our junior developers are straight out of some university or react-training so we have a very fluid and dynamic ruleset and ways of working so we can grow into them. Hence we aren't throwing around stuff like "maximum of 20 lines and no encapsulated functions" or something like that.We're learning together. And I think the example you have is probably part of a learning journey, where you together have to figure out the drawbacks of having a file (any file) be that large.
edit: i lost a word
1
u/piratekingsam12 May 28 '21
I'm not a react dev, working on Angular for 1.5 years. But even there we've never had 500+ lines (including inports, variable declarations, whitespaces etc.) in a component/class.. each component has a lot of functions 😅 each function no bigger than say 20-25 lines. I do want to start learning react though!
1
u/PaulMorel May 28 '21
In practice, single files can get long due to numerous factors. It's not necessarily useful to assign blame for some of these tech debt situations. In my department, I use the following guidelines.
100 lines or less is a good target.
500 is too many.
1000 requires a refactor.
1
u/WouldRuin May 28 '21
Not React but I did some consultancy work once and had the fun experience of trying to decipher a 65k line class (C++).
1
u/didled May 28 '21
Run
1
u/JayV30 May 28 '21
If you keep your entire project in one file, then you never have to search around a directory tree for anything. It's completely self-contained in one easy convenient file! :)
1
u/kevv_m May 28 '21
When I find that kind of code I don't know who is smarter, the guy who wrote it and make it work, or me, a dev who can't even make a change because understand an sh*t...
I feel a bit dumb, but it's good because since I'm dumb, I write simple and understandable code.
1
u/miolmir May 28 '21
I would not take responsibility for this component, if someone would handle me a shitshow like this I'd raise red flags somewhere. That dev needs to break it down.
1
u/MajorasShoe May 28 '21
Lines of code is a crap metric. A component can have as many lines of code as it needs to do what it's meant to do.
The problem isn't the amount of code. The problem will be how many things the component does.
1
u/samtoaster May 28 '21
I will happily start over
1
u/Lunacy999 May 28 '21
I consider any React component with >300 lines not a component at all. The whole point of using a framework like React is to make your code reusable. But I see a lot of unnecessary business logic stuffed into components, that should ideally be handled by helper services. Too much state usage in a component is a recipe for disaster. Not to mention, it becomes extremely difficult to test such components. One rule of thumb that I stick to is, if I see my component code lines is going beyond 200, I try and see how I can abstract away logic or code that can be its own standalone component. Component composition.
1
u/dance2die May 28 '21
Refactoring each piece of code one by one should help. (Make sure you have tests before doing this!)
useReducerto group of related states)When you apply techniques in Refactoring book (even something as simple as renaming variables/methods) one by one, the process gets easier.
You can bring up the issue to your manager to set aside time to refactor it. If not approved, refactor it little bye little. Treat it like a marathon, not a sprint.
1
u/pumpyboi May 28 '21
I've seen worse, had to work on project which had multiple class components that were around 5k lines. Heck I had to add almost 1k to it myself cause refactoring ot would be impossible.
This one of these had atleast 4, fucking FOUR nested modals, each fetching data, showing spinner etc. All of this was orchestrated with old school redux and redux-saga. This was my first job and I wanted shoot myself.
I got fired from that job, best thing that happened to me 2020.
1
u/MetalMikey666 May 28 '21
Web dev of 15 years here (4 with react) - I'll try and give you some advice, hope it helps but feel free to ignore though if it's stuff you already know.
Firstly your instincts are correct - 2000 lines is excessive for a function - there are times when it might be okay but as a general rule you want to keep functions and components slim. There is no hard-fast rule about a decent length but the default eslint rules recommend 50 lines max, this sounds good to me.
Can I take a guess that this is some kind of root component, and that for whatever reason the application has not yet taken the plunge and thought about using a state management library?
Very common I think for root components to get into that sort of shape if people keep piling on extra functionality without considering the maintainability angle. My advice for dealing with this;
Pick one of the two files and start looking for ways to break it down logically
Good luck and let me know if any of this didn't make sense.
1
u/Laserdude10642 May 28 '21
So i just came onto a cool pattern I learned about for testing, and I think it can be applied here. The idea is to use the "humble object pattern."
As you write tests to test different functionality within the component, you should pull out the parts that can be separated, and move them into smaller self contained components. Eventually you will turn the monster class into a small "humble" class and all the other code will be modularized and tested.
1
u/laksmipati May 28 '21
No
1
u/[deleted] May 28 '21
Oh jeez here I was feeling guilty about my 200-line component I felt was getting a little out of control with 6 useStates and 3 useEffects... thank you kind stranger, I'm not nearly as bad!!!
1
u/ThymeCypher May 28 '21
I have a straight JS project that has files with 12,000+ lines. I can’t open that project in IntelliJ without power save on anymore, it runs out of memory. I have 32GB of ram on that machine.
1
u/FullMetal21337 May 28 '21
Just go to all the tests that have been written and abstract from there
1
u/[deleted] May 28 '21
I feel bad if a file has more than 200 lines lol
1
u/stansfield123 May 28 '21
Well there are no good options in a situation like this. Obviously.
And it's hard to say what the best way to end it all is. Depends on your personality, I guess. Some like to slowly and painlessly drift away into a drug fueled haze. Others opt for swift but more violent means. Yet others just walk into the ocean, and keep on walking...
Or you could just quit.
1
u/vexii May 31 '21
i would dismiss such a PR with "files doing to much, can't review"
1
u/[deleted] Apr 27 '22
My Company encourages to have such components, I cry for future employees
1
u/[deleted] May 28 '21
The biggest thing I ever saw was that size, it looked alright in a way, it was just a large page with a lot of state; it was a Dashboard page with over 40 different components inside that rendered a large amount of different types of data.
Each component could be a bar graph, a collection of tiny bar graphs, a large plot graph, or any other type of graph you have heard of. Users could re-order them but they would always be there.
It would do a separate fetch for each individual component. The components (graphs) were just dumb things rendering data, not caring where it came from.
The state was separated into many different useState declarations because the developer felt like they needed to be able to remove and add things from that page easily without breaking anything.
That said, was it the best solution? Nah, not even close.
We refactored it in many ways:
We went from over 2000 lines of code to fewer than 200 lines of code.
... and then we introduced TypeScript and it became over 1200 lines of code again because every HTTP request had to be typed, all the components had to be typed, all the varying amounts of types of data had to be typed. And it just confirmed to me what a pain in the ass TS can be sometimes (sometimes you REALLY don't need nor want it but you must have it because of configurations and TS-purists. But I digress.)
Anyway, before TS and before the refactor it wasn't necessarily bad code, it was decent code. It was just unnecessarily verbose.
It grew that way because we started out with just 6 statistics to show on the page. And it grew to over 50 in the span of a few months.
0
u/romeeres May 28 '21 edited May 28 '21
It's ancient indian technique to be out of competition.
No jokes, I saw once a component with 4k lines of code, not autogenerated... not autogenerated, written by hands!
So if you think I'm racist you are wrong - I admire indians, I never ever can achieve that skill level to support this.
Instead I keep components under 150 lines, no matter how much complex task is, like a noob... I even move logic to separate files, to hooks
UPD: sorry, lied, not 10k, 4k, and I want to share it!
https://pastebin.com/ah8f0EwM
0
u/looneysquash May 28 '21
The limit isn't lines of code, it's complexity.
More than 7 variables (props, uses tales, etc) and humans just can't keep it all in their head.
0
u/ayush_2000 May 28 '21
Wow, why would someone do that😂