Our Global Presence

Canada
57 Sherway St,
Stoney Creek, ON
L8J 0J3

India
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049

USA
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
In this post, we will cover five simple React hooks that you will find handy in any project. These hooks are useful no matter the features of the application. For each hook, we will provide the implementation and the client code sample.
Web applications use modals extensively and for various reasons. When working with modals, you quickly realize that managing their state is a tedious and repetitive task. And when you have code that’s repetitive and tedious, you should take time to abstract it. That’s what useModalState
does for managing modal states.
Many libraries provide their version of this hook, and one such library is Chakra UI. If you want to learn more about Chakra UI, check out my blog post here.
The implementation of the hook is very simple, even trivial. But in my experience, it pays off using it rather than rewriting the code for managing the modal’s state each time.
import React from "react"; import Modal from "./Modal"; export const useModalState = ({ initialOpen = false } = {}) => { const [isOpen, setIsOpen] = useState(initialOpen); const onOpen = () => { setIsOpen(true); }; const onClose = () => { setIsOpen(false); }; const onToggle = () => { setIsOpen(!isOpen); }; return { onOpen, onClose, isOpen, onToggle }; };
And here’s an example of client code using the hook:
const Client = () => { const { isOpen, onToggle } = useModalState(); const handleClick = () => { onToggle(); }; return ( <div> <button onClick={handleClick} /> <Modal open={isOpen} /> </div> ); }; export default Client;
useConfirmationDialog
is another modal-related hook that we use quite often. It’s a common practice to ask users for confirmations when performing sensitive actions, like deleting records. So it makes sense to abstract that logic with a hook. Here’s a sample implementation of the useConfirmationDialog
hook:
import React, { useCallback, useState } from 'react'; import ConfirmationDialog from 'components/global/ConfirmationDialog'; export default function useConfirmationDialog({ headerText, bodyText, confirmationButtonText, onConfirmClick, }) { const [isOpen, setIsOpen] = useState(false); const onOpen = () => { setIsOpen(true); }; const Dialog = useCallback( () => ( <ConfirmationDialog headerText={headerText} bodyText={bodyText} isOpen={isOpen} onConfirmClick={onConfirmClick} onCancelClick={() => setIsOpen(false)} confirmationButtonText={confirmationButtonText} /> ), [isOpen] ); return { Dialog, onOpen, }; }
And here’s an example of the client code:
import React from "react"; import { useConfirmationDialog } from './useConfirmationDialog' function Client() { const { Dialog, onOpen } = useConfirmationDialog({ headerText: "Delete this record?", bodyText: "Are you sure you want delete this record? This cannot be undone.", confirmationButtonText: "Delete", onConfirmClick: handleDeleteConfirm, }); function handleDeleteConfirm() { //TODO: delete } const handleDeleteClick = () => { onOpen(); }; return ( <div> <Dialog /> <button onClick={handleDeleteClick} /> </div> ); } export default Client;
One thing to note here is that this implementation works fine as long as your confirmation modal doesn’t have any controlled input elements. If you do have controlled inputs, it’s best to create a separate component for your modal. That’s because you don’t want the content of the modal, including those inputs, to re-render each time the user types something.
Properly handling async actions in your application is trickier than it seems at first. There are multiple state variables that you need to keep track of while the task is running. You want to keep the user informed that the action is processing by displaying a spinner. Also, you need to handle the errors and provide useful feedback when they happen. So it pays off to have an established framework for dealing with async tasks in your React project. And that’s where you might find useAsync
useful. Here’s an implementation of the useAsync
hook:
export const useAsync = ({ asyncFunction }) => { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [result, setResult] = useState(null); const execute = useCallback( async (...params) => { try { setLoading(true); const response = await asyncFunction(...params); setResult(response); } catch (e) { setError(e); } setLoading(false); }, [asyncFunction] ); return { error, result, loading, execute }; };
The client code:
import React from "react"; export default function Client() { const { loading, result, error, execute } = useAsync({ asyncFunction: someAsyncTask, }); async function someAsyncTask() { // perform async task } const handleClick = () => { execute(); }; return ( <div> {loading && <p>loading</p>} {!loading && result && <p>{result}</p>} {!loading && error?.message && <p>{error?.message}</p>} <button onClick={handleClick} /> </div> ); }
The hook is not hard to write yourself and that’s what we often do. But it might make sense for you to use a more mature library implementation instead. Here’s a great option.
Form validation is another part of React applications that people often find tedious. With that said, there are plenty of great libraries to help with forms management in React. One great alternative is formik. However, each of those libraries has a learning curve. And that learning curve often makes it not worth using in smaller projects. Particularly if you have others working with you and they are not familiar with those libraries.
But it doesn’t mean we can’t have simple abstractions for some of the code we often use. One such piece of code that we like to abstract is error validation. Checking forms before submitting to API and displaying validation results to the user is a must-have for any web application. Here’s an implementation of a simple useTrackErrors
hook that can help with that:
import React, { useState } from "react"; import FormControl from "./FormControl"; import Input from "./Input"; import onSignup from "./SignupAPI"; export const useTrackErrors = () => { const [errors, setErrors] = useState({}); const setErrors = (errsArray) => { const newErrors = { ...errors }; errsArray.forEach(({ key, value }) => { newErrors[key] = value; }); setErrors(newErrors); }; const clearErrors = () => { setErrors({}); }; return { errors, setErrors, clearErrors }; };
And here’s the client implementation:
import React, { useState } from "react"; import FormControl from "./FormControl"; import Input from "./Input"; import onSignup from "./SignupAPI"; export default function Client() { const { errors, setErrors, clearErrors } = useTrackErrors(); const [name, setName] = useState(""); const [email, setEmail] = useState(""); const handleSignupClick = () => { let invalid = false; const errs = []; if (!name) { errs.push({ key: "name", value: true }); invalid = true; } if (!email) { errs.push({ key: "email", value: true }); invalid = true; } if (invalid) { setErrors(errs); return; } onSignup(name, email); clearErrors(); }; const handleNameChange = (e) => { setName(e.target.value); setErrors([{ key: "name", value: false }]); }; const handleEmailChange = (e) => { setEmail(e.target.value); setErrors([{ key: "email", value: false }]); }; return ( <div> <FormControl isInvalid={errors["name"]}> <FormLabel>Full Name</FormLabel> <Input onKeyDown={handleKeyDown} onChange={handleNameChange} value={name} placeholder="Your name..." /> </FormControl> <FormControl isInvalid={errors["email"]}> <FormLabel>Email</FormLabel> <Input onKeyDown={handleKeyDown} onChange={handleEmailChange} value={email} placeholder="Your email..." /> </FormControl> <button onClick={handleSignupClick}>Sign Up</button> </div> ); }
Debouncing has a broad use in any application. The most common use is throttling expensive operations. For example, preventing the application from calling the search API every time the user presses a key and letting the user finish before calling it. The useDebounce
hook makes throttling such expensive operations easy. Here’s a simple implementation that’s written using AwesomeDebounceLibrary under the hood:
import AwesomeDebouncePromise from "awesome-debounce-promise"; const debounceAction = (actionFunc, delay) => AwesomeDebouncePromise(actionFunc, delay); function useDebounce(func, delay) { const debouncedFunction = useMemo(() => debounceAction(func, delay), [ delay, func, ]); return debouncedFunction; }
And here’s the client code:
import React from "react"; const callAPI = async (value) => { // expensice API call }; export default function Client() { const debouncedAPICall = useDebounce(callAPI, 500); const handleInputChange = async (e) => { debouncedAPICall(e.target.value); }; return ( <form> <input type="text" onChange={handleInputChange} /> </form> ); }
One thing to note with this implementation: You need to ensure that the expensive function is not recreated on each render. Because that will reset the debounced version of that function and wipe out its inner state. There are two ways to achieve that:
And that’s it for this post. There are many useful hook libraries worth checking out, and if you’re interested, here’s a great place to start. While there are many helpful custom hooks out there, these five are the ones that you will find handy in any React project.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
In the current age of JavaScript, Promises are the default way to handle asynchronous behavior in JavaScript. But how do they work? Why should you understand them very well?
When we make you a promise, you take our word that we will fulfill that promise.
But we don’t tell you when that promise will be fulfilled, so life goes on…
There are two possible scenarios: fulfillment or rejection.
One day, we fulfill that promise. It makes you so happy that you post about it on Twitter!
One day, we tell you that we can’t fulfill the promise.
You make a sad post on Twitter about how we didn’t do what we had promised.
Both scenarios cause an action. The first is a positive one, and the next is a negative one.
Keep this scenario in mind while going through how JavaScript Promises work.
JavaScript is synchronous. It runs from top to bottom. Every line of code below will wait for the execution of the code above it.
But when you want to get data from an API, you don’t know how fast you will get the data back. Rather, you don’t know if you will get the data or an error yet. Errors happen all the time, and those things can’t be planned. But we can be prepared for it.
So when you’re waiting to get a result from the API, your code is blocking the browser. It will freeze the browser. Neither we nor our users are happy about that at all!
Perfect situation for a Promise!
Now that we know that you should use a Promise when you make Ajax requests, we can dive into using Promises. First, we will show you how to define a function that returns a Promise. Then, we will dive into how you can use a function that returns a Promise.
Below is an example of a function that returns a Promise:
function doSomething(value) { return new Promise((resolve, reject) => { // Fake a API call setTimeout(() => { if(value) { resolve(value) } else { reject('The Value Was Not Truthy') } }, 5000) }); }
The function returns a Promise. This Promise can be resolved or rejected.
Like a real-life promise, a Promise can be fulfilled or rejected.
According to MDN Web Docs, a JavaScript Promise can have one of three states:
"- pending: initial state, neither fulfilled nor rejected. - fulfilled: meaning that the operation was completed successfully. - rejected: meaning that the operation failed."
The pending state is the initial state. This means that we have this state as soon we call the doSomething() function, so we don’t know yet if the Promise is rejected or resolved.
In the example, if the value is truthy, the Promise will be resolved. In this case, we pass the variable value in it to use it when we would call this function.
We can define our conditions to decide when to resolve our Promise.
In the example, if the value is falsy, the Promise will be rejected. In this case, we pass an error message. It’s just a string here, but when you make an Ajax request, you pass the server’s error.
Now that we know how to define a Promise, we can dive into how to use a function that returns a Promise:
// Classic Promise doSomething().then((result) => { // Do something with the result }).catch((error) => { console.error('Error message: ', error) }) // Use a returned `Promise` with Async/Await (async () => { let data = null try { data = await doSomething() // Do something with the result } catch(error) { console.error('Error message: ', error) } })();
You can recognize a function that returns a Promise by the .then() method or an await keyword. The catch will be called if there is an error in your Promise. So making error handling for a Promise is pretty straightforward.
Promises are used in a lot of JavaScript libraries and frameworks as well. But the simplest web API is the Fetch API, which you should use for making Ajax requests.
For more information and to develop your web app using front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using JS, please visit our technology page.
Content Source:
React Native, next to Flutter and PWA, was called a revolution in cross-platform app development and delivering great mobile experience.
Code repository that’s shareable between platforms? Reusable components? That definitely sounds tempting.
React Native has been praised for its “Learn once, write anything.” objective which means you get a native look and feel of your app for both iOS and Android, and you may also include platform-specific modules.
For a developer with an experience in JavaScript, and React itself, it is easy to take up React Native and start building on it right away.
Some time ago one of our React Native apps, Guild, went public. (Update: Guild has been recognized by Red Herring’s 2019 Top 100 European Startups.)
We’re extremely proud of how the app is turning out and we just can’t wait to write more of them. Our devs and some of our clients are fully aboard the React Native train and in this post, we will tell you exactly why is that: from a perspective of a business owner and a JavaScript developer. As well as some React Native advantages and limitations.
Is React Native the pick for your next app?
Build a product your users will love to use. Get a highly performant, native app for Android, iOS, and even the Web. Work with our developers and designers to squeeze the most out of your app idea and React Native.
Unlike other cross-platform frameworks like Ionic, the Facebook team stresses they acknowledge the differences between different platforms and React Native reflects that. Therefore, you can still include modules specific for iOS and Android like status bars, navigation, or access to native elements like camera and contacts are built according to the platform.
Using libraries such as React Native for Web or ReactXP allows a developer to build a cross-platform app that runs on the Web too, so there’s no need to build separate apps at all. We used ReactXP in one of our projects and it really felt like we’re getting the Web version for free. That’s pretty amazing.
Note that using React Native DOES NOT mean you will not need any help from a native developer. If your app includes many different native features, some work on their side may be required.
Your front-end web developer can actually become a mobile developer without a need of learning iOS’s Swift or Java/Kotlin for Android. With some knowledge about native UI elements, React, and some platform-specific patterns, React Native is easy to pick up. That is a game changer in terms of building a team as your app will require just one instead of two (or even three if you’re also to conquer the Web).
You can hire JS developers who will be able to deliver for all platforms. Therefore, it is much easier for them to exchange knowledge, conduct a code review, and understand the code. What a difference it makes in terms of time and cost! Not to mention that React Native is all about bringing agility of web development to cross-platform development, with native results.
Some may argue that nothing will surpass the performance of native apps. It may be even true, but products written with React Native are almost identical in how they perform. Sometimes even better. In his great article comparing Native iOS and RN, John Calderaio says:
"(According to) the data we collected through measuring both of the application's CPU, GPU, and Memory during the tasks in each of the four tabs, the apps are also almost identical in how they perform. (…) React Native, winning two out of three categories, comes in first place as the better performing platform."
Pros:
Cons:
If you’re looking for a framework that will let you build a great cross-platform mobile app, check out Flutter.
Pic courtesy: medium.com
Bloomberg is a great example of preformant app written with React Native. Image source belitsoft.com.
When you start working with React, typically you go with a bundler like Webpack and spend some time considering the right bundling modules for your app. React Native is different, and yet it works similarly to React. It comes with everything you need to just sit down and start writing your code.
Hot/Live reload (similar to Instant Run on Android) is a beloved, killer feature that allows a developer to see introduced changes right away without complete rebuilding of the app. You don’t have to constantly check the results of actions you take which greatly boosts productivity and saves time on compilation.
When it comes to scroll, animations, buttons, text inputs and others, React Native gives an efficient recipe that allows developers to conduct basic tasks easily. Component usage is heavily simplified in comparison to native development and it’s huge.
Whereas there are countless libraries to choose from for iOS and Android, React Native does not exactly shine here. The list of third-party libraries and components is quite long, but in many cases they leave a lot to be desired. When working on modules like device sensors or push notifications, there is a chance you may need some help from a native programmer.
Truth to be told, the Facebook team together with outside collaborators and thriving population of active users constantly work on React Native making it better every day with over 2500 commits from 500 contributors last year.
According to Sophie Alpert, Engineering Manager on React:
"We're working on a large-scale rearchitecture of React Native to make the framework more flexible and integrate better with native infrastructure in hybrid JavaScript/native apps."
Even if it may happen that you’ll need to hack some existing solution or write something from scratch, this will happen more and more rarely.
Pros:
Cons:
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
Browsers don’t understand JSX out of the box, so most React users rely on a compiler like Babel or TypeScript to transform JSX code into regular JavaScript. Many preconfigured toolkits like Create React App or Next.js also include a JSX transform under the hood.
Together with the React 17 release, we’ve wanted to make a few improvements to the JSX transform, but we didn’t want to break existing setups. This is why we worked with Babel to offer a new, rewritten version of the JSX transform for people who would like to upgrade.
Upgrading to the new transform is completely optional, but it has a few benefits:
This upgrade will not change the JSX syntax and is not required. The old JSX transform will keep working as usual, and there are no plans to remove the support for it.
React 17 RC already includes support for the new transform, so go give it a try! To make it easier to adopt, after React 17 is released, we also plan to backport its support to React 16.x, React 15.x, and React 0.14.x. You can find the upgrade instructions for different tools below.
Now let’s take a closer look at the differences between the old and the new transform.
When you use JSX, the compiler transforms it into React function calls that the browser can understand. The old JSX transform turned JSX into React.createElement(…) calls.
For example, let’s say your source code looks like this:
import React from 'react'; function App() { return <h1>Hello World</h1>; }
Under the hood, the old JSX transform turns it into regular JavaScript:
import React from 'react'; function App() { return React.createElement('h1', null, 'Hello world'); }
Note Your source code doesn't need to change in any way. We're describing how the JSX transform turns your JSX source code into the JavaScript code a browser can understand.
However, this is not perfect:
To solve these issues, React 17 introduces two new entry points to the React package that are intended to only be used by compilers like Babel and TypeScript. Instead of transforming JSX to React.createElement, the new JSX transform automatically imports special functions from those new entry points in the React package and calls them.
Let’s say that your source code looks like this:
function App() { return <h1>Hello World</h1>; }
This is what the new JSX transform compiles it to:
// Inserted by a compiler (don't import it yourself!) import {jsx as _jsx} from 'react/jsx-runtime'; function App() { return _jsx('h1', { children: 'Hello world' }); }
Note how our original code did not need to import React to use JSX anymore! (But we would still need to import React in order to use Hooks or other exports that React provides.)
This change is fully compatible with all of the existing JSX code, so you won’t have to change your components. If you’re curious, you can check out the technical RFC for more details about how the new transform works.
Note The functions inside react/jsx-runtime and react/jsx-dev-runtime must only be used by the compiler transform. If you need to manually create elements in your code, you should keep using React.createElement. It will continue to work and is not going away.
If you aren’t ready to upgrade to the new JSX transform or if you are using JSX for another library, don’t worry. The old transform will not be removed and will continue to be supported.
If you want to upgrade, you will need two things:
Since the new JSX transform doesn’t require React to be in scope, we’ve also prepared an automated script that will remove the unnecessary imports from your codebase.
Create React App support has been added and will be available in the upcoming v4.0 release which is currently in beta testing.
Next.js v9.5.3+ uses the new transform for compatible React versions.
Gatsby v2.24.5+ uses the new transform for compatible React versions.
Note If you get this Gatsby error after upgrading to React 17.0.0-rc.2, run npm update to fix it.
Support for the new JSX transform is available in Babel v7.9.0 and above.
First, you’ll need to update to the latest Babel and plugin transform.
If you are using @babel/plugin-transform-react-jsx:
# for npm users npm update @babel/core @babel/plugin-transform-react-jsx
# for yarn users yarn upgrade @babel/core @babel/plugin-transform-react-jsx
If you are using @babel/preset-react:
# for npm users npm update @babel/core @babel/preset-react
# for yarn users yarn upgrade @babel/core @babel/preset-react
Currently, the old transform (“runtime”: “classic”) is the default option. To enable the new transform, you can pass {“runtime”: “automatic”} as an option to @babel/plugin-transform-react-jsx or @babel/preset-react:
// If you are using @babel/preset-react { "presets": [ ["@babel/preset-react", { "runtime": "automatic" }] ] }
// If you're using @babel/plugin-transform-react-jsx { "plugins": [ ["@babel/plugin-transform-react-jsx", { "runtime": "automatic" }] ] }
Starting from Babel 8, “automatic” will be the default runtime for both plugins. For more information, check out the Babel documentation for @babel/plugin-transform-react-jsx and @babel/preset-react.
Note If you use JSX with a library other than React, you can use the importSource option to import from that library instead - as long as it provides the necessary entry points. Alternatively, you can keep using the classic transform which will continue to be supported.
If you are using eslint-plugin-react, the react/jsx-uses-react and react/react-in-jsx-scope rules are no longer necessary and can be turned off or removed.
{ // ... "rules": { // ... "react/jsx-uses-react": "off", "react/react-in-jsx-scope": "off" } }
TypeScript supports the JSX transform in v4.1 beta.
Flow supports the new JSX transform in v0.126.0 and up.
Because the new JSX transform will automatically import the necessary react/jsx-runtime functions, React will no longer need to be in scope when you use JSX. This might lead to unused React imports in your code. It doesn’t hurt to keep them, but if you’d like to remove them, we recommend running a “codemod” script to remove them automatically:
cd your_project npx react-codemod update-react-imports
Note If you're getting errors when running the codemod, try specifying a different JavaScript dialect when npx react-codemod update-react-imports asks you to choose one. In particular, at this moment the "JavaScript with Flow" setting supports newer syntax than the "JavaScript" setting even if you don't use Flow. File an issue if you run into problems. Keep in mind that the codemod output will not always match your project's coding style, so you might want to run Prettier after the codemod finishes for consistent formatting.
Running this codemod will:
For example,
import React from 'react'; function App() { return <h1>Hello World</h1>; }
will be replaced with
function App() { return <h1>Hello World</h1>; }
If you use some other import from React – for example, a Hook – then the codemod will convert it to a named import.
For example,
import React from 'react'; function App() { const [text, setText] = React.useState('Hello World'); return <h1>{text}</h1>; }
will be replaced with
import { useState } from 'react'; function App() { const [text, setText] = useState('Hello World'); return <h1>{text}</h1>; }
In addition to cleaning up unused imports, this will also help you prepare for a future major version of React (not React 17) which will support ES Modules and not have a default export.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
It has been two and a half years since React v16 was first released. The dev team promises that update v17 is incredibly important for the future of React but claims that no new features are being added. So what exactly does that mean? And how can React claim to be releasing a major new version without adding new features?
Past React updates have always caused deprecations of older versions. This could make it incredibly difficult for teams to upgrade their React versions, especially when working with large or neglected codebases. So, the React team has decided that v17 will lay the groundwork for a new method of adopting updates. When React v18 is released, developers will be able to choose to only upgrade parts of their app and keep other parts running on v17. React advises against this if you’re application is actively maintained or in large-scale production, but it can help teams who don’t actively maintain their application or who don’t need to migrate certain components to the newer version. In the future, new React versions won’t leave these apps behind or demand massive migrations.
To enable this ability, the React team has spent some time reworking the event system. These updates are what caused React v17 to be a major release since it could potentially break many applications.
Contrary to what you might think, React doesn’t attach events to individual elements. Instead, React binds one handler per event type to the document
node. This approach increases performance in applications with large element trees and also enables features like replaying events.
In the background, React can capture an event and determine which component to call before propagating the event up the component tree. However, in native Javascript, the event has already propagated to the document
level. While this may not sound like an issue, this system breaks when running multiple instances of React. If a React app nested inside of another one has stopped the propagation of the event, the parent React app will still capture the event. This was a major headache for developers looking to nest different versions of React. You may not think that this happens in production, but the Atom code editor encountered this issue four years ago!
React will now attach event handlers to the root node of the React app. This change will allow the safe nesting of React trees within each other. Granted, all React instances will have to be running on version 17 or higher for this to work. This update also means that React apps are easier to embed inside of other frameworks like jQuery. React will now stop events from propagating to jQuery as one would expect.
It is fairly common to return a cleanup function within a useEffect
method to stop any code running within the function. In the past, this cleanup function would run synchronously before the next frame was drawn. In reality, most apps don’t require screen updates to be delayed will running cleanup methods. So they will now run asynchronously after React has rendered the next frame. This should result in faster switch times between components. You can still use the useLayoutEffect
method to run a cleanup method that blocks the render loop.
Event pooling is incredibly confusing and doesn’t provide any optimizations on modern browsers. Instead, it can result in some strange bugs when working with multiple components that receive the same event. One event handler might set the event to be null, and thus the other components using the event would run into a null variable error. In short, newer React version will allow event fields to be accessed whenever you need them.
React v17 may not be the feature-packed update React developers were hoping for. It is instead more of a piece-of-mind update. So while we may not be getting cool new components or hooks, these additions will pay off down the road in later updates. You can try React v17 now by running npm install react@17.0.0-rc.0 react-dom@17.0.0-rc.0
in your React project.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
React Router is by far the most popular library in the React ecosystem. According to npm, it is downloaded about 3.6 million times a week. This number is almost half of React’s 7.6 million weekly downloads. This means that almost every second project that uses React uses React Router.
That’s huge. Almost half of the React projects out there rely on React Router for routing. Chances are, if you have worked with React, you have worked with React Router.
Now with version six in beta and a new release coming soon, we thought it would be interesting to take a dive into what’s new and what has changed in React Router version 6.
For a library that is so important to the React community, it has gone through a number of iterations and breaking changes. From its first release in 2014, and with every major release, the maintainers of React Router have introduced new features and breaking changes. Some in the React community have complained about the difficulty of upgrading from one version to the next, and have questioned the library’s constant churn.
Many have complained about the difficult upgrades that came with every new major release of the library.
If your application is working correctly, and you don’t need access to the new features promised in version 6, you can stick with your older version. Don’t feel the need to refactor your old applications to use React Router 6. If it ain’t broke, don’t fix it.
npm install react-router@next react-router-dom@next
So without further ado, let’s take a look at what’s new and what has changed in the latest version of React Router
Routes is introduced as a new element in React Router version 6. This new element allows us to easily define nested routes and relative routes, and make it easy to compose complex routes and layouts. In the previous version of the library, we defined Routes inside of a Switch.
The <Routes > is the new <Switch> element now. It is very much similar to <Switch> with some new features.
// old - v5 import { BrowserRouter, Switch, Route } from 'react-router-dom'; const App = () => { return ( <BrowserRouter> <Switch> <Route exact path="/" component={Home} /> <Route path="/users" component={Users} /> </Switch> </BrowserRouter> ); } // new - v6 import { BrowserRouter, Routes, Route } from 'react-router-dom'; const App = () => { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="users" element={<Users />} /> </Routes> </BrowserRouter> ); }
Did that component prop got changed to element?
That brings us to our second highlight.
If you notice in the above example, in the new version we are passing a react element instead of a component. This is so much better, now we can pass props directly to the element.
// old - v5 <Route exact path="/" component={Home} /> <Route path="/users" render={routeProps => ( <Users isCustomLayout={true} /> )} /> // new - v6 <Route path="/" element={<Home />} /> <Route path="users" element={<Users isCustomLayout={true} />} />
Now, all Route and Link children of a Route are relative to their parent. This makes it a lot easier to build applications with many nested routes and makes it easier to reason about your application’s routing logic.
No more exact and strict props
Yes, you read it right. In v6 all the routes match exactly by default.
// old - v5 <Route exact path="/" component={Home} /> // new - v6 <Route path="/" element={<Home />} />
Relative paths and links
In v6, both paths and links are relative to their parent route. This means we can omit the “/” if we want the relative path.
// old - v5 <Route exact path="/" component={Home} /> <Route path="/users" component={Users} /> // new - v6 <Route path="/" element={<Home />} /> <Route path="users" element={<Users />} />
If you have used previous versions of React Router, you will immediately notice that we don’t need to use the exact prop anymore. You will also notice that the Link we defined is relative. Instead of passing /customers/:id, we can just use /:id.
What about nested routes then? They just got better.
Just like your regular react elements we just need to wrap the child route with a parent one.
// old - v5 <Route exact path="/" component={Home} /> <Route path="/users" component={Users} /> // .... users.js import { useRouteMatch } from 'react-router-dom'; const Users = () => { const { path } = useRouteMatch(); return ( <div> // you can do something here <Switch> <Route path={`${path}/:id`} component={UserInfo} /> <Route path={`${path}/profile`} component={UserProfile} /> </Switch> </div> ); } // new - v6 <Route path="/" element={<Home />} /> <Route path="users" element={<Users />}> <Route path=":id" element={<UserInfo />} /> <Route path="profile" element={<UserProfile />} /> </Route> // .... import { Outlet } from 'react-router-dom'; const Users = () => { return ( <div> // you can do something here // Outlet: This element is used as a placholder for the child route. // Which means it will be either <UserInfo /> or <UserProfile /> <Outlet /> </div> ); }
Now we can define our routes using the new useRouter hook. This allows you to build your routes using JavaScript objects. Let’s take a look at our previous application, now defined using useRouter.
import { BrowserRouter, Link, Outlet, useRoutes } from 'react-router-dom'; function App() { let element = useRoutes([ { path: '/', element: <Home /> }, { path: 'customers', element: <Customers />, children: [ { path: '/', element: <CustomersIndex /> }, { path: ':id', element: <CustomerProfile /> }, ] } ]); return element; } function Users() { return ( <div> <nav> <Link to="/1">Customer 1</Link> </nav> <Outlet /> </div> ); }
You might ask yourself, why does it matter? Why would I want to compose my routes using JavaScript objects instead of JSX? One great use case would be to programmatically build routes, let’s say, based on the directory structure of your application. You could loop through all of the files in your pages directory, and build routes from that.
The team behind React Router claims that the new version is a lot smaller than the previous versions. They estimate that it’s about 70% smaller. Smaller bundles mean that your application loads faster, and content to your users faster.
With all these awesome changes, there is also icing on the cake. They have reduced the bundle size by more than 50%.
Pic courtesy: medium.com
The old useHistory hook has been removed and replaced with a suspense-ready navigate API. Now you can use useNavigate to programmatically navigate around your application. They also expose a Navigate component that you can use to redirect your users.
No more history, it’s time to navigate. The useHistory hook is now replaced with the suspense-ready useNavigate hook.
// old - v5 import { useHistory } from 'react-router-dom'; const CustomButton = props => { const history = useHistory(); const handleClick = () => { history.push('/users'); } return <button onClick={handleClick}>{props.label}</button>; } // new - v6 import { useNavigate } from 'react-router-dom'; const CustomButton = props => { const navigate = useNavigate(); const handleClick = () => { navigate('/users'); } return <button onClick={handleClick}>{props.label}</button>; }
So that’s it! If you believe that your applications can benefit from smaller bundle sizes, and from suspense ready navigation, we strongly suggest that you upgrade to the latest version.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
In the frontend development world, we oftentimes need to have up-to-date data on the client. And to achieve that there are several options at our disposal:
While the first to are preferred, polling still is an important tool especially in situations when our backend can’t provide us with WS or SSE. And in this article, we will be reviewing how to use polling with arguably the most widely-used state manager in the JavaScript realm – Redux.
There are two basic types of polling – Short and Long. For the sake of simplicity, we will be reviewing only Short polling. It’s the easiest one to implement – all it does – sends requests from the client-side to the server at a certain fixed interval. For example, let’s say we have a small website that shows the current weather in a selected region. And to keep the client up-to-date we can use the Short polling technique, that is, send client-to-server requests (for weather data) every 30 seconds. And, therefore, approximately (time between responses might differ) every 30 seconds we will be getting new weather data.
Now, let’s see how we can implement polling in React & Redux application. In our examples, we’ll continue working on the weather application and see how it can be realized using different techniques.
The most naive implementation would be by using the “setInterval” function in the “componentDidMount” method (or the “useEffect” hook).
In this implementation, we’re creating the “updateInterval” variable that points to an actual interval function after it’s being initialized in the “componentDidMount” life cycle method. The interval dispatches the “getWeatherData” redux-action every 30 seconds and does so continually while the component is mounted.
class WeatherApp extends Rect.Component { updateInterval; componentDidMount() { this.updateInterval = setInterval(() => { this.props.getWeatherData(); }, 1000 * 30); // 30 seconds } componentWillUnmount() { clearInterval(updateInterval); } render() { return ( <div> {this.props.weatherData} </div> ); } }
The biggest downside of this approach is that business logic (pulling data) is tight to the view. The other problem is that the “setInterval” function doesn’t wait till the previous action call (from the “setInterval” body) is completed. Therefore, this version can be improved by using the “setTimeout” function, with the help of which we can start each next cycle only when the previous one is completed. Thus, we won’t accidentally run into a situation where we have two (or even more) calls simultaneously (might happen in the case with “setInterval” on when we have small delays between cycles).
Here is our improved version with the use of the “setTimeout” function.
class WeatherApp extends React.Component { updateTimeout; componentDidMount() { this.getWeatherData(); } getWeatherData = async () => { await this.props.getWeatherData(); this.updateTimeout = setTimeout(this.getWeatherData, 30 * 1000); } componentWillUnmount() { clearTimeout(updateTimeout); } render() { return ( <div> {this.props.weatherData} </div> ); } }
We would like to point out that it’s not an actual code from production, just an example. And there is a good chance that async/await won’t be a viable option because the “getWeatherData” function most likely won’t be an asynchronous function – in such instances, we can use callbacks.
Nevertheless, even this improved version is still not good enough because we didn’t resolve the main problem – a tight connection between business logic and the presentation layer. And one of the drawbacks of previous solutions is that the update logic is defined in components thus making it hardly reusable.
By creating a custom action that will encapsulate all the “update by timeout” logic in action’s body – we can address the reusability drawback mentioned earlier and untight the connection between layers.
export const initActions = async dispatch => { let updateTimeout; getWeatherDataTimedout = async () => { await dispatch(getWeatherData()); updateTimeout = setTimeout(getWeatherDataTimedout, 30 * 1000); } /** Initialize any other actions */ getWeatherDataTimedout(); } class WeatherApp extends React.Component { componentDidMount() { this.props.initActions(); } render() { return ( <div> {this.props.weatherData} </div> ); } }
Again, it’s a simplified version. And the “initActions” function can be easily extended by adding custom parameters that can be passed from containers and by adding more actions that can be dispatched in the action’s body.
But we should look for another approach if we want to unentangle the “update by timeout” logic from the View as much as possible.
One of the ways to achieve that level of disentanglement is to use Redux middlewares.
The concept is quite straightforward – middleware is some sort of a middleman between dispatching actions and actual execution of those same actions in the reducer.
With all that in mind, we can create a middleware for the “getWeatherData”:
const getWeatherDataTimedout = async dispatch => { await getWeatherData()(dispatch); setTimeout(() => updateMessages(dispatch), 30 * 1000); }; const getWeatherDataMiddleware = ({ dispatch }) => next => { getWeatherDataTimedout(dispatch); return action => next(action); };
But just creating middleware is not enough, it should be “registered” at the global store. To do so we can use the “compose” function inside of the “createStore” as follows:
const store = createStore( rootReducer, compose(applyMiddleware(/** other middlewares */, getWeatherDataMiddleware)) );
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone while being compatible with the newest features of React.
While working with react you might have noticed that are different ways to manage the global state management in React. Let’s take look at the options that we have:
Redux is a predictable state container for JavaScript apps.
It is used by a lot of web apps these days, it allows us to have a global state, register components to it and they will re-render by themselves every time a value they registered to will change.
Context API is another approach that devs take for better management of state within the application.
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
Now that we are already using to above two famous ways of adding global state to our application here comes something new i.e Recoil.
Recoil lets you create a data-flow graph that flows from atoms (shared state) through selectors (pure functions) and down into your React components.
React
local component state. If the same atom is used from multiple components, all those components share their state.Let’s try to understand this with a Demo example.
Consider we want to store user data upon login into our application and share between two components,
Let first define an atom which stores the logged-in user Data
pic courtesy: blog.bitsrc.io
In the above example, we have stored the object which has a name in it. It is stored inside our loggedInUserData
atom.
Now consider we need to show this name in our useRecoilState
.
pic courtesy: blog.bitsrc.io
And our component looks something like this, which display the data from the same atom which is used in the header component again with help of useRecoilState
pic courtesy: blog.bitsrc.io
The syntax might look quite similar to useState which we are already used to in react
hooks.
As in the above example since the same state is shared between the
This is one of the important hooks in the Recoil API. This hook will just subscribe to the component to the given Recoil state, it is used to return the value of the given Recoil state.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.
Content Source:
Babel is a JavaScript compiler that includes the ability to compile JSX into regular JavaScript.
Array.from
and built-ins like Promise
are only available in ES6+, but they can be used in older environments if a Babel polyfill is.@babel/register is often used in Node.js. It makes the babel run dynamically when the require
code is executed. Since it’s not popular way to run babel in React, we are not going to deal with @babel/register way.
Let’s Create sample project.
— Create a directory and package.json
mkdir test-babel-how cd test-babel-how npm init -y
— Install the necessary packages
npm i @babel/core @babel/cli @babel/plugin-transform-arrow-functions @babel/plugin-transform-template-literals @babel/preset-react
— Create a sample code
src
folder and create code.js
in the src
folder.test-babel-how | -- node_modules -- src | -- code.js -- package-lock.json -- package.json
const element = <div>babel test</div>; // 1 const text = `element type is ${element.type}`; // 2 const add = (a,b)> a + b; // 3
We are going to:
— run the following command in the terminal
npx babel src/code.js // 1 --presets=@babel/preset-react // 2 --plugins=@babel/plugin-transform-template-literals, // 3 @babel/plugin-transform-arrow-functions
src/code.js
.@babel/preset-react
.@babel/plugin-transform-template-literals
& @babel/plugin-transform-arrow-functions
.— Following output in the terminal
const element = /*#__PURE__*/React.createElement("div", null, "babel test" ); // 1 const text = "element type is ".concat(element.type); // 2 const add = (a, b) > a + b; // 3
concat
method.— install packages to use webpack
npm i webpack webpack-cli babel-loader
— create a babel.config.js
file
const presets = ['@babel/preset-react']; const plugins = [ '@babel/plugin-transform-template-literals', '@babel/plugin-transform-arrow-functions' ]; module.exports = { presets, plugins };
babel.config.js
to specify presets & plugins.— create a webpackge.config.js
file
const path = require('path'); module.exports = { entry: './src/code.js', // 1 output: { // 2 path: path.resolve(__dirname, 'dist'), filename: 'code.bundle.js', }, module: { // 3 rules: [{ test: /\.js$/, use: 'babel-loader'}], }, optimization: { minimizer: []} , // 4 }
dist/code.bundle.js
file.babel-loader
to handle JavaScript files.babel.config.js
file.— run webpack
npx webpack
— dist/code.bundle.js
is created with a following output:
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; // ... // ... /* 0 */ /***/ (function(module, exports) { const element = /*#__PURE__*/React.createElement("div", null, "babel test"); // 1 const text = "element type is ".concat(element.type); // 2 const add = (a, b) > a + b; // 3 /***/ }) /******/ ]);
// ...
part is webpack’s run time code.— create runBabel.js
file
const babel = require('@babel/core'); // 1 const fs = require('fs'); const filename = './src/code.js'; const source = fs.readFileSync(filename, 'utf8'); // 2 const presets = ['@babel/preset-react']; // 3 const plugins = [ '@babel/plugin-transform-template-literals', '@babel/plugin-transform-arrow-functions', ]; const { code } = babel.transformSync(source, { // 4 filename, presets, plugins, configFile: false, // 5 }); console.log(code); // 6
code.js
to compiletransformSync
function— run file
node runBabel.js
const element = /*#__PURE__*/React.createElement("div", null, "babel test" ); // 1 const text = "element type is ".concat(element.type); // 2 const add = (a, b) > a + b; // 3
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop any custom web apps using React JS, please visit our technology page.
Content Source:
React 16.13.0 contains bugfixes and new deprecation warnings to help prepare for a future major release.
A React component should not cause side effects in other components during rendering.
It is supported to call setState
during render, but only for the same component. If you call setState
during a render on a different component, you will now see a warning:
Warning: Cannot update a component from inside the function body of a different component.
This warning will help you find application bugs caused by unintentional state changes.
In the rare case that you intentionally want to change the state of another component as a result of rendering, you can wrap the setState
call into useEffect
.
When dynamically applying a style
that contains longhand and shorthand versions of CSS properties, particular combinations of updates can cause inconsistent styling. For example:
<div style={toggle ? { background: 'blue', backgroundColor: 'red' } : { backgroundColor: 'red' } }> ... </div>
You might expect this <div>
to always have a red background, no matter the value of toggle
. However, on alternating the value of toggle
between true and false, the background color start as red
, then alternates between transparent
and blue
, as you can see in this demo.
React now detects conflicting style rules and logs a warning. To fix the issue, don’t mix shorthand and longhand versions of the same CSS property in the style
prop.
String Refs is an old legacy API which is discouraged and is going to be deprecated in the future
<Button ref="myRef" />
For example, it will fire if you use String Refs together with the Render Prop pattern:
class ClassWithRenderProp extends React.Component { componentDidMount() { doSomething(this.refs.myRef); } render() { return this.props.children(); } } class ClassParent extends React.Component { render() { return ( <ClassWithRenderProp> {() => <Button ref="myRef" />} </ClassWithRenderProp> ); } }
Code like this often indicates bugs. (You might expect the ref to be available on ClassParent
, but instead it gets placed on ClassWithRenderProp)
You most likely don’t have code like this. If you do and it is intentional, convert it to React.createRef()
instead:
class ClassWithRenderProp extends React.Component { myRef = React.createRef(); componentDidMount() { doSomething(this.myRef.current); } render() { return this.props.children(this.myRef); } } class ClassParent extends React.Component { render() { return ( <ClassWithRenderProp> {myRef => <Button ref={myRef} />} </ClassWithRenderProp> ); } }
React.createFactory
is a legacy helper for creating React elements. This release adds a deprecation warning to the method. It will be removed in a future major version.
Replace usages of React.createFactory
with regular JSX. Alternately, you can copy and paste this one-line helper or publish it as a library:
let createFactory = type => React.createElement.bind(null, type);
When React 16 was released, createPortal
became an officially supported API.
However, we kept unstable_createPortal
as a supported alias to keep the few libraries that adopted it working. We are now deprecating the unstable alias. Use createPortal
directly instead of unstable_createPortal
. It has exactly the same signature.
React adds component stacks to its development warnings, enabling developers to isolate bugs and debug their programs. This release adds component stacks to a number of development warnings that didn’t previously have them. As an example, consider this hydration warning from the previous versions:
pic courtesy: reactjs.org
While it’s pointing out an error with the code, it’s not clear where the error exists, and what to do next. This release adds a component stack to this warning, which makes it look like this:
pic courtesy: reactjs.org
This makes it clear where the problem is, and lets you locate and fix the bug faster.
This release contains a few other notable improvements:
shouldComponentUpdate
. This shouldn’t affect most code, unless you have side effects in shouldComponentUpdate
. To fix this, move the code with side effects into componentDidUpdate
.onMouseEnter
now doesn’t trigger on disabled <button>
elements.version
export since we published v16. This release adds it back. We don’t recommend using it in your application logic, but it’s useful when debugging issues with mismatching / multiple versions of ReactDOM on the same page.React v16.13.0 is available on the npm registry.
To install React 16 with Yarn, run:
yarn add react@^16.13.0 react-dom@^16.13.0
To install React 16 with npm, run:
npm install --save react@^16.13.0 react-dom@^16.13.0
We also provide UMD builds of React via a CDN:
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
For more Information and to build a website using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using React JS, please visit our technology page.
Content Source:
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
© 2025 — HK Infosoft. All Rights Reserved.
© 2025 — HK Infosoft. All Rights Reserved.
T&C | Privacy Policy | Sitemap