DEV Community

Cover image for Are you using React ? Then I think you must know this

Posted on

Are you using React ? Then I think you must know this

At the time of writing this, React is at version 17.02. It is fascinating to see the exponential growth of this library. Everyone one is writing code in the react with the amusing speed and efficiency. But, still there are plenty of rabbit holes where most of the programmers got into the jargon.

If you are using react for a while, then I think you have faced the weird behavior of react sometimes like :

  1. Tooooo many re-renders error
  2. Async behavior of setState() etc.

So, In this article I will touch over some of the situations where we have to be careful πŸ”

βœ‚ Destructure Props With Default Values :-

React Components heavily relies on the data forwarded using props. Whether it is a state object or a callback function. Handling props and destructing them before actual using them is one of good practice. It makes your code less error prone and more robust in order to sustain the uncertain behavior of inputs

const ChildComponent = ({ username = null }) => {
            return (
                <p> Hello ! {username ?? "Anonymous"} </p>

Enter fullscreen mode Exit fullscreen mode

Here, In this snippet props are destructured with default values to avoid undefined error. Also, while using the props are used with ?? operator to avoid any further conflicts

😷 Using useMemo() :

Every state change comes with the cost of re-rendering the virtual DOM. Sometimes this re-render is less costly, but sometimes it does make the difference. So, when re-render happens every bit of code inside the function body is re-defined and it is unnecessary to re-render the Dumb Code. Because, it is not going change its functionality. hence, we use ** useMemo() **

const ExecuteCounter = React.memo((data, callback) => {
<button onChange={callback}> Increment </button>

Enter fullscreen mode Exit fullscreen mode

As, everyone can notice, the execute counter is DUMB Components. Hence, here it is wrapped in the memo(). This will re-render the ExecuteCounter() only when the props are changed.

πŸ”¨ setState() is async :

setState() is async in nature. When we call the setState() in the callback function, it is not going to update the state instantly. rather, it will batch the any subsequent changes and then apply them once it's done. This avoids the several heavy lifting because the setState() applies huge computations while re-rendering

This is probably the haven't estimated by many but, it's worth mentioning it here. Reason behind making the setState() async is pretty simple. As JavaScript is single threaded, making the setState() synchronous can block the browser's main execution thread and ultimately results in the unresponsive page. Hence, to avoid this the React's DEV team created the setState() as async in nature.

This is experienced by many dev's if we immediatly querying state values after we call the setState()

πŸŽ‰ Use thunk() :

If anyone already using redux may know this, but still I will explain It. Making async changes in the redux reducer is pretty easy with actios. But, any newbie ever tried to make ajax requests from the actions of the redux, then here is the trick,

while creating store in redux, we have to wrap the redux thunk inside the create store

import thunk from 'redux-thunk'

const middelware = [thunk]

const store = createStore(rootReducer, applyMiddleware(middelware))

Enter fullscreen mode Exit fullscreen mode

After this you can dispatch the async request from the action creaters like this

const get userInfo = (userId) => async (dispatch) => {
   try {
    //fetch data 

    dispatch({ type : "ACTION_TYPE" : payload : "VIRUS"})

   } catch (err) {
     console.log("err", err.message")


Enter fullscreen mode Exit fullscreen mode

This, is simplistic example of thunk. We can exploit it to do more actions then that of simple ajax requests

😎 Final Views :

Re-rendering the components in react cost us more. Avoid re-rendering of the dumb code can significantly increase the render speed and avoid the any pitfall or lag in the interaction between the user and the we application

Thanks For Reading πŸ™

Top comments (5)

lexlohr profile image
Alex Lohr

I wrote something that relates to your article:

Anyways; useMemo in your example will not help at all; the fiber that holds the component will only rerender when its props changes, same as useMemo. An example where it would actually help: if you had a callback that had to be created dynamically inside your component or whatever you used inside there was computation-heavy.

Also, for ajax requests, you need no redux nor thunks. The second last example of my post shows how to do it in an effect.

jackmellis profile image

Definitely some misleading things in this piece:
There's a difference between memo and useMemo, they are totally different (although they do complement each other), you should also be careful not to just memo everything as this can often be more expensive than just recalculating. There are plenty of articles and metrics on this topic.
Calling setState async is misleading. Yes it batches your state updates until the end of the render cycle, but it's not async in the classic sense. Async is associated with promises and delayed callbacks.
Don't take this as criticism of your writing, sharing and creating content is great, I just want to clear up some (pretty common) misconceptions

sudarshansb143 profile image

Thank you jack for your explanation it is pretty good ! πŸ™

Although my point of mentioning the memoization is closely related to how we can 'cache' the dumb components and avoid them from re-rendering. Although, after reading your point, I will definitely take deeper look into this.

I am calling setState() as async in the sense of it's execution, as compared to other sync code like classical for -- of loop.

Although, I want to thank to you for this. I will take it as a helpful note and I will definitely improve myself in my next one😎

Make sure you criticize that also πŸ˜…πŸ˜…

sudarshansb143 profile image

Thanks for feedback !
I will try to keep content as relevant as possible in my upcoming articles.