Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
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
Download now
Download
Save Best Practise For Later
Download
Save
Save Best Practise For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
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
Download now
Download
Save Best Practise For Later
Carousel Previous
Carousel Next
Save
Save Best Practise For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 14
Search
Fullscreen
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 ATP12, 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)Gunernome8iv5 2) ve (taerscap((ser) > 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 internaltimproves 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 withLikewise, 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 «buttonrs? 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 aRecommended 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 + Membership1 Medium Sign up to discover human stories that deepen your understanding of the world. Fre one
You might also like
React Coding Standards
PDF
50% (2)
React Coding Standards
14 pages
React Native - Guideline
PDF
No ratings yet
React Native - Guideline
3 pages
65+ JavaScript Code Snippets - With Explanations
PDF
No ratings yet
65+ JavaScript Code Snippets - With Explanations
71 pages
ReactJS Best Practices
PDF
No ratings yet
ReactJS Best Practices
25 pages
Chapter 04 - Talk Is Cheap, Show Me The Code Digital Notes
PDF
No ratings yet
Chapter 04 - Talk Is Cheap, Show Me The Code Digital Notes
6 pages
The Only React Cheat Sheet (+ PDF) You Need - Zero To Mastery
PDF
No ratings yet
The Only React Cheat Sheet (+ PDF) You Need - Zero To Mastery
36 pages
React Cheatsheet Zero To Mastery V1.02
PDF
100% (1)
React Cheatsheet Zero To Mastery V1.02
36 pages
ReactJS
PDF
No ratings yet
ReactJS
9 pages
ReactJS - Guideline
PDF
No ratings yet
ReactJS - Guideline
3 pages
React concepts
PDF
No ratings yet
React concepts
9 pages
ReactTopics
PDF
No ratings yet
ReactTopics
5 pages
React From Zero Sample Chapter React From Zero Sample
PDF
No ratings yet
React From Zero Sample Chapter React From Zero Sample
36 pages
Js Snippets
PDF
No ratings yet
Js Snippets
10 pages
JavaScript Concepts For React Js
PDF
No ratings yet
JavaScript Concepts For React Js
6 pages
React JS Update V2
PDF
No ratings yet
React JS Update V2
32 pages
React Js
PDF
No ratings yet
React Js
13 pages
Reactjs en Events
PDF
No ratings yet
Reactjs en Events
37 pages
React 6 Tips
PDF
No ratings yet
React 6 Tips
13 pages
ReactJS_Geeks4Geeks
PDF
No ratings yet
ReactJS_Geeks4Geeks
4 pages
React Tips
PDF
No ratings yet
React Tips
201 pages
Learning JSX Summary Notes-3158
PDF
No ratings yet
Learning JSX Summary Notes-3158
14 pages
Harry React CheatSheet
PDF
No ratings yet
Harry React CheatSheet
40 pages
REACT
PDF
100% (1)
REACT
22 pages
React Js Notes
PDF
No ratings yet
React Js Notes
19 pages
Ep4ReactNotes
PDF
No ratings yet
Ep4ReactNotes
3 pages
React Tutorial 2020
PDF
50% (2)
React Tutorial 2020
34 pages
React 101
PDF
No ratings yet
React 101
8 pages
ReactJS_Handwritten_Notes
PDF
No ratings yet
ReactJS_Handwritten_Notes
111 pages
Hacking With React
PDF
100% (1)
Hacking With React
123 pages
Lec 3
PDF
No ratings yet
Lec 3
17 pages
Notes of React Masterclass Feb 13
PDF
No ratings yet
Notes of React Masterclass Feb 13
30 pages
React Note
PDF
No ratings yet
React Note
6 pages
React Fundamentals
PDF
No ratings yet
React Fundamentals
18 pages
React Chap-2
PDF
No ratings yet
React Chap-2
21 pages
React Course PDF
PDF
No ratings yet
React Course PDF
35 pages
React Architecture Patterns for Your Projects
PDF
No ratings yet
React Architecture Patterns for Your Projects
24 pages
JavaScript Best Practices
PDF
No ratings yet
JavaScript Best Practices
16 pages
React Midterm Recap
PDF
No ratings yet
React Midterm Recap
12 pages
React JS Intro
PDF
No ratings yet
React JS Intro
19 pages
Lecture # 12 - Introduction To React JS
PDF
No ratings yet
Lecture # 12 - Introduction To React JS
76 pages
Every React Concept Explained in 5 Minutes - DEV Community
PDF
No ratings yet
Every React Concept Explained in 5 Minutes - DEV Community
18 pages
React Notes
PDF
No ratings yet
React Notes
567 pages
Case Study
PDF
No ratings yet
Case Study
13 pages
10 JavaScript Concepts For React PDF
PDF
No ratings yet
10 JavaScript Concepts For React PDF
12 pages
Mark Erikson - Introduction To React, Redux, and TypeScript (2020)
PDF
100% (1)
Mark Erikson - Introduction To React, Redux, and TypeScript (2020)
111 pages
Reactjs Roadmap For Beginners
PDF
No ratings yet
Reactjs Roadmap For Beginners
9 pages
Delightful React Code and Sketches
PDF
100% (1)
Delightful React Code and Sketches
90 pages
React JS
PDF
No ratings yet
React JS
27 pages
React JS1
PDF
No ratings yet
React JS1
7 pages
React Cheat Sheet
PDF
No ratings yet
React Cheat Sheet
35 pages
101_react_tips_and_tricks
PDF
No ratings yet
101_react_tips_and_tricks
142 pages
React Tips
PDF
No ratings yet
React Tips
2 pages
FSD-II Notes
PDF
No ratings yet
FSD-II Notes
25 pages
React
PDF
No ratings yet
React
8 pages
React Cheat
PDF
No ratings yet
React Cheat
24 pages
React-Dev-Learn
PDF
No ratings yet
React-Dev-Learn
17 pages
React Fundamentals
PDF
No ratings yet
React Fundamentals
9 pages
React Points
PDF
No ratings yet
React Points
12 pages