0% found this document useful (0 votes)
6 views

Best Practise

best Practise for react

Uploaded by

ml6893254
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
6 views

Best Practise

best Practise for react

Uploaded by

ml6893254
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 14
React.js Best Practices Best Practices for Clean React Apps Roopa Saran Faow Reacts a frontend framework and one of the most popular JavaScript libraries for building user interfaces on the web, With its diverse features, i te awide alot of flexibil y of applications. We may provides be writing code and building great Uls that are working, However, writing code just to create apps isnt enoughs the code should he clean and readable e apps. Clean code isnot just code that works, tohelp us develop maintainab but rather code that can he easily read, reused, refactored, extended, and sealed by others. Hence, we should write code in a manner that should be self-explanatory, easy to read and understand, and help in ensuring ‘This blog aims o present a compiled version of some widely accepted writing style are practices to keepin mind while working with React that should be helpful to both intermediate and experienced develope 1.Use Object Destructuring: ‘Object destructuring allows you to take specific fields from an abject and assign them to variable instantly. Itseduces the numberof code lines we need to extract the object properties and makes your code easier to sat deal of explicit variable understand, Object destructuring saves = ‘9. Array Destructuring: ‘An often overlooked E86 features array destructuring, It allows us to access array values without specifying indexes. ons cooery = optitorae(i}: ‘4.Use Template Literals: Use template literals to build large strings. Avoid using string concatenation. IS nice and clean, ve ure cds fuarbetateh 1800} '5.1Sx Short Hane: Use SX shorthand for passing explicit true boolean props to Components For example, if you want to make your ttle visible in your NavBiae Component: 6. Use Ternary Operators: For cases where we knov that we expect only 2 possible options, use ternary ‘operators, Lets say you want to show a particular user's details based on. role. [Notice inthe following examples how the above code causes the equality check tobe evaluated 2 times, While with ternary, we can lower itto once. "7-Take Advantage of Object Literals: Object literals can help make our code more readable, Lets say you want to show three types of users based on their roles. Using ternary isnot suggested because the numberof options i greater than two (it would need nesting). Object literals can be used instead, : ve Cone (rote } = user birwovee: txploycetser, const Component * componentsirotel: {In addition to increasing readability in such scenarios, we can also employ object literals to map dynamic or computed properties. 8.Use Fragments: Always use Fragment aver div of span as containers, It keeps the code clean ‘ands also beneficial for performance because we are not adding useless containers tthe DOM tre, hence one less node is created in the virtual Dom. ‘9, Don't Define a Function Inside Render: DDontt define a function inside render. Move any JS code out of Xf that doesnt serve any purpose of rendering or UI functionality Try to keep the logic inside render to an absolute minimum. a canta Lgtotet-taget, "eUtchaa"; /) Avoid ate » ve onst supttota = (event) => ¢ “anole lglevets target, "eLihed")s 10, Reusing Expressions with Variables: Declare variables in the block scope code for reusability. As soon as you see ‘the need to use condition or expression more than onee, extract itas.a variable instead of repeating the expressions over and over, oe fntion getertreferencen(vser) ( WF eberseriactatarese === ow) ( 3 Gal ie (sercenfcontatasrote == ones") { 1 , ve ‘ction getertreferencen(vser) ( inet (rote ) sureraaretotate; 1 Mae (rote ) , men) ‘1.String Props Don't Need Curly Braces: ‘when being passed toa child component. oe ‘Soar eeteECMY ATP 12, Lists and the Key prop: “The “key” prop isa special string attribute you need to include when ‘rendering lists of elements, React uses keys to uniquely identify items in an array. With keys, React can pinpoint which item has been changed, added, or ‘removed from the array. ‘Most ofthe time when rendering arrays, we might tend to use the index as the key. While this sometimes works, using the index as a key can introduce issues especially ifthe lists expected to change. Consider this list - va farromp((elan, inden) => et hey=(eten>(etem 7109) 13, Arrowfunetions & implicit return: Use the JavaScript feature of implicit return in arrow functions to write Deautifal code, Let’ say your function does a simple calculation and returns the result finttion aie, { retcn eb} ‘Similarly while using the arrow function in ISX 8 faaerbnep((oner) => (_ return cy hey=(oser.$d)Gunernome che beyetunetd)>furernane 1860) 14 Import Ordering: Always try to import things in the following recommended order The rule of, ‘thumb iso keep the import order like this: Builein External internal timproves code readability. Most editors like VSCode provide an option to automatically order the imports on file save. oe srt colors fran) )eylefestors ‘Sort ( Prepyoes Tran “orp: tyes': 15.File & Folder Structure: (One ofthe most commonly followed files & folder structures sas fllows:- pre + assets — Contains static assets — Icon Svgs, banner images etc. + /eomponents — reusable components lke navigation, buttons, forms 1 (services — JavaSript modules + /atils — utilities, helpers, constants + /iewsipages ~The majority ofthe app pages would be here tH indexis appis |nturn, each component folder should have its respective files grouped, ‘under the seme. This maintains a consistent hierarchy throughout the codebase. Bg. For the footer component, the necessary files could include ‘srejeorponents/foster/indextox, sre/conponents/feoter/sty1es.5658, srefeonponents/foster/stories.tsr, sre/eonponents/footer/feoter.testststy 16, Naming Conventions: Always use PasealCase for components and camelCase for instances & prop a at fornepar © om fro roe nnber= (1245675) ve Prenton (128670) ‘TLNaming Rationales: ‘Boolean variables, or functions that return a boolean value, should start with Likewise, functions should be named for what they do, not how they do it In ‘other words, don't expose details ofthe implementation in the name. Why? ‘Because how you doit may change somedy, and you shouldn't need to ‘refactor your consuming code because oft. For example, you may load your config from a REST API today, but you may decide to bake itinto JavaScript tomorrow, Also, avoid underscores in function names. (dosonethir()) 18, Reserved Prop Name Usage: Don't use DOM component prop names for passing props between ‘components because others might not expect these names. ye ykarpanne eeytectaaet® > 19, Usage of Quotes: Use double quotes for JSX attributes and single quotes for al other JS. a ‘o testuresslerrrst ine! 33 J> oe Beeler ereeet ieee 20.SX in Parentheses: fe J8X thats being returned by your component or iterator spans more than one line, always wrap itin parentheses. or"? yeni /> ; “ent > 2, Selt-closing Tags: |fyour component doesnt have any children, then use self-closing tags. It ‘improves readability. 122, Santize HTML to prevent XSS Attacks: ‘Maybe you've found yourself in asconario where you have to use the ‘property dangerouslySetinnerlITML.on an element in React, say when having to render the result coming from a rich text editor. Basically, its ‘React’ equivalent to Javascripts innerHTML, const marag = 2 » rpTMs 1 set via dngerustsettme HTM" ructyetianerhTs({ nen Nesting 9) 735 ‘The term dangerously is chosen with intention. Using this property can open you up toa cross-site scripting (XSS) attack. Sots highly recommended that ‘the code that gets sets sanitized First. You could ether use a custom-written _utdity to ter out risky code snippets or use external libraries to help with this, bonpursty is one good example ofthis. 23, Using Spread Operator to pass Props: -fyou have an object, and you want to pass ll ts Keys in SX, you can use a “spreae!” syntax to pass the whole object. Ithelps with avoiding ‘unnecessary abject property access & repetition. ‘rotictcard nme(itemsnane)priceftemprice) > ve promictcard (Stet > 24, Using Optional Chaining: Increases readability and simplifies otherwise long logical conjunctions and ‘complex-looking conditions (ott showtshers = bake ptshars. length 225. Shorthand Logic Evaluation: Below are some examples of cases that return truthy/falsy values that can be ‘relatively shortened, fusing such coneitions injevascript code blocks like function, they can be ye Sree = Soar) ‘fused inside JSX, they can be frst converted to Boolean using the double negation (1) operator as: ue (Cater as (inane 6 26. Img Alt prop Always include an alt prop in your tags. And, we dont need to use pletures or images in ale property because the screen readers already announce ing elements as images. 27, Detault Props: Itis considered a good practice to seta default value for otherwise optional ops. Const Noor = (( showesFications 1) = 1 2. Inte styles: Itisnot considered good practice to use inline styles in React components Always make use of options lke stylesheets, CSS modules, styled. components, ete “LaiToeylett toptys ‘nore! tereclete 28, Async/await over Callbacks: Promises & callbacks have been the pillar pattern for working with asynchronous code, However, the introduction of asyneawait has helped achieve the same functionality, in addition to providing better readability ‘and overcoming certain limitations like issues with nested callbacks (callback hells) ete. oe ec rntoe/eoptacenlae typ icode conjures") then (resoene) = ranponae jun) ‘ant (repens) = canelertotreepree) jsten (ort) = sane. crrariar)t ve ye function getuserad) aa st reponse = ant fot tsps/seonplacetelser pate. con/usrs®); a eat ‘xnele togtcees}+ : + , 90. Use Error Boundaries: As much as we try to make our application robust, errors are still bound to ‘occur, We create user friendly Uls to handle such error cases. To guard our app against crashing entirely, React provides the feature of Error boundaries ‘through which we can display a fallback UI should an unexpected error ‘oceur, You can make use of Reacts Erroroundary implementation as shown below or use a package like resct-errorsbounary oe tien component Cmponent » ve te errorsoundary oitense East coment ( “aetructor(prps) ‘per oes) fhisstate "(hackers false 25 a scat getertvdstatetrenrvorfrrar) reeom (fosters eve 1 comonenosecateh(erron, errortnfo) Tegterorlerror,errvinfol, 1 renser SF ohisatatenasreer) return cgay something went wrong. ch , d conse App = 0 ead ‘31, Functional Components over Class Components: ‘With the introduction of hooks, theres practically nothing that you canitdo {in Functional components as opposed to class components, nd functional ‘components are better because: ‘They are much easier to read and test because they are plain JavaScript functions, # You end up with less code. also, the resulting translated version is ‘comparatively Tess. Irgets easier to separate container and presentational components ‘because you need to think more about your component’ state if you don't Ihave access to setState() in your component, ‘The React team recommends them stating they provide a performance Dost. 8 ass vel extends Reatecomoonent ( renaer() Teorm ‘Meloy (hiscpropsane (hts ve eeurn cute, fone A , ‘92, Use memotzation techniques: Understanding the render eyele ofa component can help us in leveraging ‘the various memoization options provided by React to improve the performance of your application and avoid unnecessary re-rendering, (especially when dealing with heavy or logically expensive components & computations). Some memoization techniques include: «© React.PureComponent (for class components) fe memo() # useCallback) fe useMtemog) However, we can not go about memoizing every eomponentin our application since even memoizaton uses memory and can be less perforant when used incorrectly. Therefore, the only caveat is knowing ‘whether any such memoization technique is needed or not and when tose it [Below isan example ofa case when using mene is beneficial oe oor const typ = 02> {ans (usrhane oetverione] = woeSeste(3h0" reurn - cos sagan urosne(ucetaee) > fogcton onc Lek Cineronent> Tern «button rs? cons eh acorponent = (( sete 3) = Although the chitécanponsnt should render only once because the value of “count” has nothing todo with the chitéconponent But it renders each time you clickon the button, A better way would be to change ch técorponent to this: ve ‘osotetogt reser) Fearn ie forerane 2 bi 6 a G Written by Roopal Jasnani @Qeo Merton Roepe cod @ © - sonarqube \ © evs en foes Understanding Design Patternsin Setupan instance of SonarQube Reset ‘and integrate it with GitHub... Desi patemearerepeatalesckitonsto __Setyp asl: nosedintanc of SonarQabe commontysccuringdevdopmet probe fr cinco auomatc code analy. Gm Qs 6a a Recommended from Medium © aumenacn © cot ‘Top 10 Tips To Optimise Your React 4 Lessons learned from using ‘Application [NextJS 13 in production Bai 2s ‘toes totap You Grown go |B comings Develsoment © pcceteetinr @ reno Using NGINX as APIGateway ‘Say Goodbye to Debouncing: Use sow “useDeferredValue” Hook © coanpanney cots seney rou sev sasacone + Membership 1 Medium Sign up to discover human stories that deepen your understanding of the world. Fre one

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy