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

sudarshan - May 15 '21 - - Dev Community

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) => {
return({
<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 🙏

. . . . . . . . . . . . . .
Terabox Video Player