DEV Community

Cover image for React best practices and patterns to reduce code - Part 2

React best practices and patterns to reduce code - Part 2

Rahul Sharma on March 18, 2022

I've another article about React best practices and patterns to reduce code. It's a good article to read before you start to write your own React c...
Collapse
 
ekdikeo profile image
Eric B

Use object state if you have to update multiple states together

Not really, no. Use useReducer.

Use styled-components

No.

Use object(Map) instead of switch statement

... while there are places where this does make sense, especially if you're in a component that is otherwise 100% declarative, for the most part, avoid.

Use object destructuring instead of passing multiple props by name to a component

Absolutely not. Always pass exactly the parameters you need. Do not ever pass a wholesale ...rest props to a component.

Use fragment

Wow! OK, I was not aware of Fragment. Great tip . . . when it's useful. It has a specific purpose, and your example is not it.

Collapse
 
ianhfar profile image
ianhfar

"Use styled-components to style your components."
This should be highlighted as your opinion.
Not sure you can argue this is a must.

By separating your styling into a css file, you are not polluting your source with styling.

Collapse
 
devsmitra profile image
Rahul Sharma

Thanks for suggestions, I've added.

Collapse
 
cteyton profile image
Cédric Teyton

Hello Rahul, FYI we've added your blog post on a GitHub project gathering content about best coding practices :)
github.com/promyze/best-coding-pra...

Collapse
 
stunaz profile image
stunaz • Edited

About the last exemple on the key : why not use the key in SomeComponent even if you dont use the key. i.e. like :

return (
  <>
    {list.map((item) => (
        <SomeComponent  key={item.id}/>
    ))}
  </>
);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
devsmitra profile image
Rahul Sharma

Thanks for pointing it out, I've missed one more component. I meant was this

return (
  <>
    {list.map((item) => (
      <React.Fragment key={item.id}>
        <SomeComponent />
        <SomeComponent />
      </React.Fragment>
    ))}
  </>
);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ebitzu profile image
Info Comment hidden by post author - thread only accessible via permalink
eBitzu

Please delete sections of your article you don't know how they really work. The worst thing you can do is to teach people bad stuff

  1. Multiple setState are now batched.

  2. Functions outside of jsx but inside component are basically the same thing, new function on every render

  3. Props destructoring is considered bad practice

  4. React.Fragment suports key

Collapse
 
johnsoriano profile image
John Soriano • Edited

All your complaints are addressed in this post.

  1. He said multiple states can be batched. there are notes. are you read the post?
  2. Isn't re-render or re-evaluate the function because it wraps in useCallback, you just have pass to deps in order not to re-evaluate. please educate.
  3. Who said destructuring is bad practice? it's one of Javascript edge, as long as you know the props being passed.
  4. React.Fragment he said that, are you reading the post?
Collapse
 
devsmitra profile image
Rahul Sharma

@johnsoriano Has already answered few of questions.

React batching is not available in the current react version. It'll be available for react-18, react-18 is rc releasead.

Collapse
 
ebitzu profile image
eBitzu • Edited

Stop saying I don't read the article, as the article was updated after my comments. Use you brain...

Batching is available in 17, but not for async situations like setTimeout

Thread Thread
 
devsmitra profile image
Rahul Sharma • Edited

I agreed, but that's why I added setTimeout in my example. I've not updated article example, I just added note of react 18.

Collapse
 
msaperst profile image
Max Saperstone

This is a great article. One thing I've done in the past is setup ESLint to catch some things like this. I'll look to see if I can add some more, but it'll auto catch and even fix a lot of these things

Collapse
 
anishde12020 profile image
Anish De

This is quite an useful article!

I have 1 question, what is wrong with using props like className for component props? Maybe I have a Button component that has some pre-defined styles but I will also keep the option to add more styles later on (say margins or text size) using the className prop whenever I re-use the component. Will it be not a better way than declaring variants for every possible situation?

Collapse
 
devsmitra profile image
Rahul Sharma • Edited

You can use there is no hard and fast rule, But try to avoid for any custom prop. let say you have button component you want 2 types of button contained and ghost, so don't use like style="ghost" or style="contained".

const type = "ghost" === props.style ? "something" : "something"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anishde12020 profile image
Anish De

Ah, I see.

Collapse
 
dommirr profile image
dommirr

it's good to know React.memo to avoid unnecessary renders. But I think it is more important to know how to make good use of React.memo since we tend to misuse it.

Collapse
 
devsmitra profile image
Rahul Sharma

Good point, I'll add note for that. Thank you for pointing it out 😊

Collapse
 
gabrielmlinassi profile image
Gabriel Linassi • Edited

I'd add some more:

  1. Composition
  2. Extract useEffect logic into a custom hook
  3. Try to use useRef instead of useState for inputs
  4. Don't put into state info you can get from reading other states

Examples:

<Layout>
   <Layout.SidePanel>{ ... }</Layout.SidePanel>
   <Layout.Main>{ ... }</Layout.Main>
</Layout>
Enter fullscreen mode Exit fullscreen mode
const { cart, loading, error } = useCart()
...
return cart.items.map(item => (...))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
manssorr profile image
Mansour Koura

HEY MAN! YOU ARE AWESOME!

  • Use object(Map) instead of switch statement. I've already mentioned the same in my previous article for reducers.
  • Use styled-components to style your components. This is a good way to avoid writing CSS in JSX and also helps to avoid CSS setup for the application.
  • Use object state if you have to update multiple states together.
  • Don't write functions inside JSX elements.

All of those ones Realy amazing! and I will start using them immediately, please write more!

Collapse
 
techfortified profile image
Peter Kelvin Torver

"Use React.memo() wisely, don't use memo where component often re-renders with props."
Can u explain why? Supposing I have a child component that takes props, what you suggest I should? Don't call React.memo() on the child component?

Collapse
 
devsmitra profile image
Rahul Sharma

don't use memo where component often re-renders because of props. React.memo does not help because it's anyway going re-render.

Collapse
 
mariolemus profile image
Mario Lemus

Pretty good content, ¡thanks!

Collapse
 
vzpintor profile image
vzpintor

Can you share me the article
Use object(Map) instead of switch statement. I've already mentioned the same in my previous article for reducers.

I don't have clearly why es better use man instead of switch

Collapse
 
devsmitra profile image
Rahul Sharma

dev.to/devsmitra/react-best-practi...

Point number 2, It's almost similar to redux-toolkit.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
devsmitra profile image
Rahul Sharma • Edited

Thanks Alexandr, But in this article I've not used any difficult words. Only heading that can converted into another language, I believe that much also all software engineers/students can understand.

Collapse
 
Sloan, the sloth mascot
Comment deleted
 
devsmitra profile image
Rahul Sharma • Edited

My point is heading can understand by anyone, it does not require expertise in english. Code anyway not going to change.

Thread Thread
 
doberman2029 profile image
Alexandr

Okay, thanks btw

Thread Thread
 
devsmitra profile image
Rahul Sharma • Edited

@doberman2029 You can translate, but make sure you add the original blog link also.

Collapse
 
sharan98727 profile image
sharan

const onClick = useCallback(() => {
setCount(1);
// ...
}, [deps]);

return (


Click

);

Why are we using usecallback here. is there any specific reason here.

Collapse
 
nokternol profile image
Mark Butterworth

If setCount was the only thing called then it would be pointless but all these hooks are just different forms of memoization used for different purposes.

useCallback creates a cached method preventing a re-render if the deps did not change. useState dispatcher already does this so memoizing it alone adds no value.

Collapse
 
dmytro_dmytro_dmytro profile image
Dmytro Dmytro

Useful! Thanks! I would recommend to read this one: webman.pro/blog/react-best-practices/

Collapse
 
xlcyanz profile image
Johan Ezequiel S. Linares

For the last example of the keys, could Children.ToArray be used?

Collapse
 
devsmitra profile image
Rahul Sharma

Actually, my intention was to show if we have 2 components, that could be the same or different. I think my example is creating confusion, I've updated the example hope that helps.

Collapse
 
slopez93 profile image
Santi López Bayo

You can comment also here:

eccco.space/s/cadf73c1-1900-4fe8-a...

Some comments have been hidden by the post's author - find out more