Content Source:
- medium.com
React components are small, reusable pieces of code that return a React element to be rendered to the page. The simplest version of the React component is a plain JavaScript function that returns a React element. Components can be broken down into distinct pieces of functionality and used within other components. Components can return other components, arrays, strings, and numbers. A good rule of thumb is that if a part of your UI is used several times (Button, Panel, Avatar), or is complex enough on its own (App, FeedStory, Comment), it is a good candidate to be a reusable component.
In most applications, there is a need for input and some form of interaction with users, allowing them to type something, upload a file, select a field, and so on. React deals with user interaction it in two distinct ways – controlled and uncontrolled components.
The value of controlled components, as their name suggests, is controlled by React by providing a value to the element that interacts with the user, while uncontrolled elements do not get a value property. Thanks to that, we have a single source of truth which happens to be the React state, so there is no mismatch between what we are seeing on the screen and what we currently have in our state. The developer needs to pass a function that will respond to user interaction with a form, which will change its state.
class ControlledInput extends React.Component { state = { value: "" }; onChange = (e) => this.setState({ value: e.target.value }); render() { return ( <input value={this.state.value} onChange={this.onChange} /> ); } }
In uncontrolled React components, we do not care about how the value changes, but if we want to know the exact value, we simply access it through ref.
class UncontrolledInput extends React.Component { input = React.createRef(); getValue = () => { console.log(this.input.current.value); }; render() { return ( <input ref={this.input}/> ); } }
So which should be used when? I would say that controlled components are the way to go in most cases, but there are some exceptions. For example, one case where you need to use uncontrolled components in React is the file type input, as its value is read-only and cannot be programmatically set (user interaction is required). Also, I find controlled components easier to read and easier to work with. Doing validation for controlled components is based on the rerender, the state can be changed, and we can easily indicate that there is something wrong with the input (e.g., format or being empty).
We already mentioned refs, which are a special feature that was available in class components until hooks appeared in 16.8.
Refs can give the developer access to a React component or DOM element (depending on the type where we attach ref) through reference. It is considered a good practice to try to avoid them and use them only in must-have scenarios, as they make the code a bit harder to read and break the top-to-bottom data flow. Yet, there are cases where they are necessary, especially on DOM elements (e.g., changing focus programmatically). When attaching to a React component element, you can freely use methods from within that component that you are referring to. Still, this practice should be avoided as there are better ways to deal with it (e.g., lifting state up and moving functions to parent components).
Refs also have three different ways they can be accomplished:
Finally, there are cases when refs aren’t passed down and times when you want to access a deeper reference element from the current component (e.g., you have a <Button> component that has an inside <input> DOM element and right now you are in a <Row> component, and from the row component you want to have access to input the DOM focus function. That’s where you would use forwardRef).
One case where reference is not being passed down is when there is a higher order component being used on a component—the reason is quite understandable as ref is NOT a prop (similar to key) so it isn’t being passed down so it will be referencing the HOC instead of the component being wrapped by it. In such a case, we can use React.forwardRef which takes props and refs as arguments, which can be then assigned to prop and passed down to the component that we want to access.
function withNewReference(Component) { class Hoc extends React.Component { render() { const {forwardedRef, ...props} = this.props; return <Component ref={forwardedRef} {...props}/>; } } return React.forwardRef((props, ref) => { return <Hoc {...props} forwardedRef={ref} />; }); }
The more complex things get, the higher the probability that something will go wrong. That’s why error boundaries are a part of React. So how do they work?
If something goes wrong and there’s no error boundary as its parent, it will result in the whole React app failing. It is better to not display information rather than mislead users and display wrong information, but it doesn’t necessarily mean that you should crash the whole application and show a white screen. With error boundaries, you have an added degree of flexibility that you can use. You can either use one across the whole app and display an error message, or use it in some widgets and simply not display them, or display a small amount of information in place of those widgets instead.
Remember that it is only about issues with declarative code rather than imperative code that you write for handling some events or calls. For these, you should still use the regular try/catch approach.
Error boundaries are also a place where you can send information to the Error Logger that you use (in the componentDidCatch lifecycle method).
class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, info) { logToErrorLogger(error, info); } render() { if (this.state.hasError) { return <div>Help, something went wrong.</div> ; } return this.props.children; } }
Higher Order Components (HOC) are often mentioned in React and are a very popular pattern, one that you will probably use (or already did so). If you’re familiar with HOCs, you’ve probably seen withNavigation, connect, withRouter in many libraries.
HOCs are just functions that take a component as an argument and will return a new component with extended capabilities compared to the one without the HOC wrapper. Thanks to that, you can achieve some easily extensible functions that could enhance your components (e.g., access to navigation). HOCs can also take a few forms called depending on what we have, the only argument always required being a component, but it can take extra arguments—some options, or like in connect, you first invoke a function with configurations that later returns a function which takes an argument component and returns HOC.
There are a few things that you could add and should avoid:
export function importantHoc() { return (Component) => class extends React.Component { importantFunction = () => { console.log("Very Important Function"); }; render() { return ( <Component {...this.props} importantFunction={this.importantFunction} /> ); } }; }
Styling is not necessarily related to React itself but it is worth mentioning for a number of reasons.
First of all, the regular CSS/inline styles apply here as normal and you can simply add class names from CSS in the className attribute, and it will work correctly. The inline styling is a bit different than the regular HTML styling. The string is not being passed down with styles but rather objects with correct values for each. Style attributes are also camelCased, so border-radius becomes borderRadius and so on.
React seems to have popularized a few solutions that became commonplace not only in React, such as CSS modules that were recently integrated within CRA, where you can simply import name.modules.css and use its classes like properties to style your component (some IDEs, e.g., WebStorm, also have Autocomplete for that, which tells you what names are available).
Another solution that is also popular in React is CSS-in-JS (e.g., the emotion library). Just to point out again, CSS modules and emotion (or CSS-in-JS in general) are not limited to React.
Stay tuned to get upcoming react js blog on React Hook and Performance.
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:
React is a standout amongst the most open source code libraries made for JavaScript software engineers. It is centered on the most agreeable and simple approaches to build up an application or a website page. It’s utilized for taking care of view layer for web and Mobile applications. React likewise enables us to make reusable UI collection of components.
Less Complex
React is just simpler to grasp right away. When compared to Angular – if we really need to do that – it is much simpler. React utilizes an exceptional language structure called JSX which enables you to blend HTML with JavaScript. This isn’t a prerequisite; Developer can in any case write in plain JavaScript however, JSX is substantially less demanding to utilize.
Perfect Entry
At the time Angular 2.x was reported by Google, alongside the retrogressive inconsistency and significant changes it would bring. Moving from Angular 1 to 2 resembled moving to an alternate framework so this alongside execution speed enhancements that React guaranteed made it something developers were anxious to attempt.
Let us take a quick look on the advantages of React over other advanced technologies or frameworks with the front-end world changing consistently.
Development Flexibility
The primary job in that process was played by the side-libraries, which give you a few exceptional chances. For example, as a developer, one is currently ready to conquer a few limitations and preclusion inside a coding procedure while picking the most agreeable and comprising methods for dealing with certain issues.
Native Approach
React can be used to create mobile apps with React Native, and React is source of re-usability, meaning extensive code re-usability is supported. So at the same time we can make iOS, Android and Web application.
Virtual DOM
The utilization of Virtual DOM is another imperative development. On account of that expansion you can make an in-memory information structure store and specify goals contrasts. Accordingly, you can refresh the program’s shown DOM proficiently.
Data Binding
React utilizes one-way data binding and an application design called Flux controls the stream of information to parts through one control point – the dispatcher. It’s simpler to troubleshoot independent parts of extensive React applications.
Advanced App Performance
The development of React diminished the issue of falling behind different applications created on similar stages. React consequently refreshes one-page applications that frequently don’t require reloads for the UI redraws.
SEO Friendly
A standout amongst the most imperative issues of JavaScript systems is that don’t fit well with search engines. As an outcome, this mismatch has negative implications for your website page or application with a lower search engine positioning. React is prepared to help tackle such an issue. It gives you a chance to run your application on a server, while as of now featured virtual DOM would have the capacity to render and come back to the program as a normal site page. In this way, there is no requirement for PhantomJS.
Testability
React applications are super easy to test. React views can be treated as functions of the state so we can manipulate with state we pass to the React view and take a look at the output and triggered actions, events, functions, etc.
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.
One of main frustrations when it comes to Create React App, or really any frontend app that is served statically without a server backing it, is that your routes are now gone. You can access them from inside the app and go from page to page but if you try to access a page directly – well, this happens: https://isthereuber.in/leiria ( ‘404 The requested path could not be found’ )
This is not okay, the website is static but the user doesn’t need to know.
We will now need to create a nginx configuration for our server. The reason to choose nginx over node is mostly because it has been proven to be faster for static assets but you can totally do this with node.
A configuration file for nginx is a nginx.conf file so let’s start by creating that file and start coding it:
# auto detects a good number of processes to run worker_processes auto; #Provides the configuration file context in which the directives that affect connection processing are specified. events { # Sets the maximum number of simultaneous connections that can be opened by a worker process. worker_connections 8000; # Tells the worker to accept multiple connections at a time multi_accept on; } http { # what times to include include /etc/nginx/mime.types; # what is the default one default_type application/octet-stream; # Sets the path, format, and configuration for a buffered log write log_format compression '$remote_addr - $remote_user [$time_local] ' '"$request" $status $upstream_addr ' '"$http_referer" "$http_user_agent"'; server { # listen on port 80 listen 80; # save logs here access_log /var/log/nginx/access.log compression; # where the root here root /var/www; # what file to server as index index index.html index.htm; location / { # First attempt to serve request as file, then # as directory, then fall back to redirecting to index.html try_files $uri $uri/ /index.html; } # Media: images, icons, video, audio, HTC location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ { expires 1M; access_log off; add_header Cache-Control "public"; } # Javascript and CSS files location ~* \.(?:css|js)$ { try_files $uri =404; expires 1y; access_log off; add_header Cache-Control "public"; } # Any route containing a file extension (e.g. /devicesfile.js) location ~ ^.+\..+$ { try_files $uri =404; } } }
This is a pretty standard configuration for nginx and we tell it where to show our files and what the cache expiration date is. There is also some helpers for 404 and logs.
We don’t enable gzip here but for an example with it you can look here.
Now that we have our nginx config we can now create our Dockerfile and we will start by stating what is the base image we will be using:
FROM nginx:1.15.2-alpine
After this we need to tell docker what it needs to run our app and in this case we need to do three things:
Details on how to do this are below:
FROM nginx:1.15.2-alpine COPY ./build /var/www COPY nginx.conf /etc/nginx/nginx.conf EXPOSE 80
Now to finish our Dockerfile we need to tell it what command to run and for that we will the nginx cli and pass it as the entrypoint in our Dockerfile:
FROM nginx:1.15.2-alpine COPY ./build /var/www COPY nginx.conf /etc/nginx/nginx.conf EXPOSE 80 ENTRYPOINT ["nginx","-g","daemon off;"]
As you can see we run nginx with -g daemon off; so that nginx stays in the foreground so that Docker can track the process properly (otherwise your container will stop immediately after starting).
You can now build and tag this image with:
docker build --rm -f Dockerfile -t rick-morty-random-episode:latest .
And then run it with:
docker run --rm -d -p 80:80 rick-morty-random-episode:latest
If you use now you can just deploy this as it is and now will build and run the image on their own servers.
We now have static routes on our static projects! If someone hits any route on your webapp this will be redirected to index.html and your app will work flawlessly.
For more Information and to build web app using React.js, Hire React.js Developer from us as we provide you high quality services 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 app using React.js, please visit our technology page.
Content Source:
With React is urging us to migrate to the new Context API. Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In React, data is often passed from a parent to its child component as a prop
.
This method has worked well in the past, but is not suitable for every kind of data. It will make things difficult later when moving components around. props
even get passed down to child components which aren’t using the data.
The truth is that Context has been a part of React for a really long time.
Remember the <Provider>
tag that we used earlier in the Redux app? It is actually a part of the older React Context API. React Context API is even used by libraries such as react-redux, MobX-react, react-router, and glamorous.
So why is React Context API making such a big noise now?
React used to discourage developers from directly using it in their apps and it was only included on an experimental basis. Now, with official support + the ability to render props, Context brings us a delightful new experience.
The new context API consists of three main steps:
React.createContext
is passed the initial value. It returns an object with a Provider
and a Consumer
.Provider
component is used higher in the tree and accepts a prop called value. This value can be anything!Consumer
component is used anywhere below the Provider
in the tree and accepts a prop called children
and must be a function that can accept a value and return a JSX.Let’s take an in-detail look at how to use React Context API by migrating the earlier app from Redux to React Context API.
First, let’s remove all traces of Redux from our code. Delete the Reducer.js
and Actions.js
from the src
folder.
You can also remove the redux
and react-redux
dependencies. Simply run:
$ yarn remove redux react-redux
With that taken care of, let’s begin writing our app with React Context API.
To convert the previous app to Context API, I first need to create a context to store the data in. This context will replace the Redux Store.
I will also have to create a Context.Provider
component, which will act just like a normal React component. This React component will have a state and props and a component lifecycle.
Create file named Provider.js
in the src
folder. Inside, store the default values in the state and pass them down in the render
, through the value prop.
import React from 'react'; import Char from './hero'; const DEFAULT_STATE = { allChar: Char, searchTerm: '', }; export const ThemeContext = React.createContext(DEFAULT_STATE); export default class Provider extends React.Component { state = DEFAULT_STATE; searchTermChanged = searchTerm => { this.setState({searchTerm}); }; render() { return ( <ThemeContext.Provider value={{ ...this.state, searchTermChanged: this.searchTermChanged, }} > {this.props.children} </ThemeContext.Provider> ); } }
Provider.js
Note: You can use the same hero.js
file as the one you had used in the Redux version of the app. Use the same code snippet as the one I had showed above.
export default [ { name: 'Amethyst', alter_ego: 'Amy Winston', first_appearance: 'LEGION OF SUPER-HEROES #298 (1983)', }, { name: 'Aquaman', alter_ego: 'Arthur Curry', first_appearance: 'MORE FUN COMICS #73 (1941)', }, { name: 'Arsenal', alter_ego: 'Roy Harper', first_appearance: 'ADVENTURE COMICS #250 (1958)', }, { name: 'Atom', alter_ego: 'Ray Palmer', first_appearance: 'SHOWCASE #34 (1961)', }, { name: 'Batgirl', alter_ego: 'Barbara Gordon', first_appearance: 'BATMAN #139 (1961)', }, { name: 'Batman', alter_ego: 'Bruce Wayne', first_appearance: 'DETECTIVE COMICS #27', } ];
hero.js
In most cases, we’ll want to render {this.props.children}
, as we’re likely to just render this component class high up in our component tree, above any place where we might want to consume it.
We want our action handlers to be able to modify our state, and propagate its value down. So we will create component methods that will call this.setState
to trigger re-renders. Furthermore, if we want to make those action handlers available later down the tree, we will need to also make them accessible in the value prop.
To consume these values later in the component tree, we will need to create a ThemeContext.Consumer component
. This component will need a render prop that will receive the above value prop as an argument.
Create another file called Consumer.js
in the src
folder and write the following code in it.
import React from 'react'; import {ThemeContext} from './Provider'; export default class Consumer extends React.Component { render() { const {children} = this.props; return ( <ThemeContext.Consumer> {({allChar, searchTerm, searchTermChanged}) => { const char = searchTerm ? allChar.filter( char => char.name.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1 ) : allChar; return React.Children.map(children, child => React.cloneElement(child, { char, searchTerm, searchTermChanged, }) ); }} </ThemeContext.Consumer> ); } }
Consumer.js
We will leave the App.js
file as it is, except make sure to remove the import statement for react-redux
and actions
.js file. We only have one thing left to do. Open your index.js
file and inside the render()
function, wrap the App
component inside <Consumer>
component and wrap that inside the <Provider> component as shown here:
import React from 'react'; import ReactDOM from 'react-dom'; import Provider from './Provider'; import Consumer from './Consumer'; import App from './App'; ReactDOM.render( <Provider> <Consumer> <App /> </Consumer> </Provider>, document.getElementById('root') );
index.js
And with that, we have a simple React App that uses React Context API to manage its state.
Each app is different, which also means that each app’s needs are different.
Some apps may work best with Redux, while others may work best with React Context API.Others might even need something like Mobx or Mobx-State-Tree, and some may not need anything to handle their state at all.
So, how do you decide?
The answer comes with experience. But I will try help you make your decision by explaining some of the best use cases for Redux and React Context API.
The point at which we want to start thinking about Redux is when our app’s state is global.
But you will probably have very less amount of state that will be global.Which brings us to an important take away:
Use both local and global state in your apps.
Managing everything in Redux is overkill. It may have negative performance implications and will increase the complexity of your app, making it hard to refactor, and likely reduce the reusability of many of your components.
But I am going off on a tangent here. Getting back to the topic, when do I use Redux?
Say you are building a food-ordering website. We have a checkout page that shows the food items a user has ordered with their respective prices and the total checkout price.
We manage all of this state with a local component state in the Checkout component. Then, we implement the NavBar component which shows the number of food items in the user’s cart and the total checkout price.
But we already have this data managed and rendered in the Checkout component. Also, you want both the Checkoutcomponent and NavBar component to stay in sync as the contents of the cart change. In other words, we have two disparate components that need to read and possibly update the same state.
So you need to pull the checkout cart state of our Checkout component up into Redux. Once this data is in Redux, the Checkout and NavBar components can individually connect to Redux with the state and dispatch functions they need.
React Context API is used when all you want is a simple state management. It can also be used in apps where you want to pass some props deeply without the overkill that comes with Redux or MobX.
But the new Context API has its own limitations.
For example, it encourages the use of immutable or persistent data structures or strict comparison of context values which might prove difficult because many common data sources rely on mutation.
Another limitation is that the new Context API only allows for a Consumer to read values from a single Provider type, one consumer to one provider. Unlike the current API, which allows a Consumer to connect to multiple Providers.
For more Information and to build website using React.js, Hire React.js Developer from us as we give you 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 app using React.js, please visit our technology page.
Content Source:
Let’s describe the problem first, we’ll discuss about the solution with some example code to cover it in this article.
React-router and react-transition-group are two widely used libraries that can be combined to create transitions between routes.
However, in react-transition-group, once a component is mounted, its exit animation is specified, not changeable. Thus, dealing with transitions depending of the next state (what we call dynamic transitions) is challenging with this library.
The exiting transition of state A does not depend only from state A (“dynamic transition”)
it is not easy to tweak it to create more sophisticated use cases such as dynamic transitions. In this article, we’ll explain how to do so thanks to react-router v4 and react-transition-group v2.
If you are on your way developing transitions between pages of your react app, you might have already met this code snippet. (adapted with state A/B):
<TransitionGroup> <CSSTransition key={location.key} classNames="fade" timeout={300}> <Switch location={location}> <Route exact path="/state-a" component={A} /> <Route exact path="/state-b" component={B} /> </Switch> </CSSTransition> </TransitionGroup>
Understanding why this piece of code allows a transition between two routes is not obvious. However, it is necessary to implement a more sophisticated use case such as dynamic transitions.
About TransitionGroup
When transitioning from state A to state B, location.key
value changes (let’s say from A
to B
) so without a <TransitionGroup>
wrapping <CSSTransition key={location.key}>
, the <CSSTransition key='A'>
would be unmounted and a new <CSSTransition key='B'>
would be mounted (because react identifies elements thanks to key).
However, <TransitionGroup>
tracks its children by key and when one of its children disappears, it keeps rendering it for the time of the transition. So during the time of the transition, the above TransitionGroup would render something similar to this:
<div> <CSSTransition key='A' leaving> <Switch location={location}> <Route exact path="/state-a" component={A} /> <Route exact path="/state-b" component={B} /> </Switch> </CSSTransition> <CSSTransition key='B' entering> <Switch location={location}> <Route exact path="/state-a" component={A} /> <Route exact path="/state-b" component={B} /> </Switch> </CSSTransition> </div>
About Switch
You simply need to understand that when location.pathname
is /state-a
, this:
<Switch> <Route exact path="/state-a" component={A} /> <Route exact path="/state-b" component={B} /> </Switch>
it renders:
<A />
Why you need to pass a location prop to the switch?
By default, a switch uses history.location
to select the route to render. However you can provide a location prop to the switch
that will override the default history.location
value:
<TransitionGroup> <CSSTransition key={location.key} classNames="fade" timeout={300}> <Switch location={location}> <Route exact path="/state-a" component={A} /> <Route exact path="/state-b" component={B} /> </Switch> </CSSTransition> </TransitionGroup>
So why this location
(provided by withRouter
or available within a route component) must be added as a prop to the switch in a transition use case?
history.location
is a live object whereas the location
provided by withRouter
is immutable. Thus, without providing a location
prop to the switch, the switch would always match the route according to the current location (the location of history.location
). So during the transition (the current location is B
), the <TransitionGroup>
would render:
<div> <CSSTransition key='A' leaving> <B /> </CSSTransition> <CSSTransition key='B' entering> <B /> </CSSTransition> </div>
However, if you pass a location to the switch, the switch will use this prop instead of history.location
and since location
is immutable, the previous <CSSTransition>
received the previous location
and the new <CSSTransition>
receives the new location
.
<div> <CSSTransition key='A' leaving> <A /> </CSSTransition> <CSSTransition key='B' entering> <B /> </CSSTransition> </div>
Thereby the leaving <CSSTransition>
will still render an old route even if a new location has been pushed to the history.
Dealing with dynamic transitions is not straight forward. An issue on react-transition-group is open to consider this problem.
As explained in the issue:
once a component is mounted, its exit animation is specified, not changeable.
Indeed, in this code snippet:
<TransitionGroup> <CSSTransition key={location.key} classNames="fade" timeout={300}> <Switch location={location}> <Route exact path="/state-a" component={A} /> <Route exact path="/state-b" component={B} /> </Switch> </CSSTransition> </TransitionGroup>
only the current (entering) child is accessible. The exiting one has already been removed. It is only living within the <TransitionGroup>
state.
Fortunately the <TransitionGroup>
component can receive a childFactory
.
So the childFactory
prop makes it possible to specify the leaving transition of a component after rendering it (and thus solves the problem of dynamic transitions)
<TransitionGroup childFactory={child => React.cloneElement( child, {classNames: "newTransition", timeout: newTimeout} )} > <CSSTransition key={location.key}> <Switch location={location}> <Route exact path="/state-a" component={A} /> <Route exact path="/state-b" component={B} /> </Switch> </CSSTransition> </TransitionGroup>
In the above code snippet, the previous <CSSTransition>
will be updated with the new transition class name and timeout.
The question is now: how do you give the right classNames value according to the state transition?
A possible solution is to use the location state.
Here is how you could do:
// state-a.js export default (props) => ( <div> <button onClick={() => { history.push({ pathname: '/state-b', state: {transition: 'fade', duration: 300} }) }} >Go to state B</button> <button onClick={() => { history.push({ pathname: '/state-c', state: {transition: 'slide', duration: 500} }) }} >Go to state C</button> </div> )
In the routes definition file:
<TransitionGroup childFactory={child => React.cloneElement( child, { classNames: location.state.transition, timeout: location.state.duration } )} > <CSSTransition key={location.key}> <Switch location={location}> <Route exact path="/state-a" component={A} /> <Route exact path="/state-b" component={B} /> </Switch> </CSSTransition> </TransitionGroup>
Now you should get 2 different transitions from the same exiting state. This is what we were trying to solve.
For more Information and to build web app using React.js, Hire React.js Developer from us as we provide you high quality services 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 app using React.js, please visit our technology page.
Content Source:
The popularity of React seems to be ever growing. React is leading in popularity in Stack overflow’s 2017 most loved component libraries.
React’s virtual DOM, the ability to declaratively describe a user interface and model the state of that interface, low barriers to entry for a decent JavaScript developer, all make React a great go-to library for building UI’s.
Another great reason for working with React is components. Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. To help kickstart your work with React components, here are 10 great React component libraries you should consider for your next app.
Many of these libraries can also be combined with Bit, which enables you to isolate and manage components in any SCM repository, share them to a Scope to make components individually available to discover and install, and keep them synced between different repositories and projects.
React Material-UI is a set of React components that implements Google’s Material Design. With over 30k stars on GitHub, it is probably the most popular React component library. The library’s v1 is coming up.
React-Bootstrap is a reusbale React component library with the look-and-feel of Twitter’s popular Bootstrap. At over 11k stars, its simplicity receives wide popularity in the community.
React Toolbox is a set of React components that implements Google Material Design specification. It’s built on top of some the trendiest proposals like CSS Modules (written in SASS), Webpack and ES6. The library’s website provides a live component playground.
React Belle is a set of React components optimized to work both on mobile & desktop devices. The styles are highly customizable so you can configure the base styles of all the components as well as modify each one of them individually. Here is also a nice example.
React Grommet provides a rich selection of components grouped by usage classifications, and all components are accessible, cross-browser compatible and support theme customization.
Material Components Web is developed by a core team of engineers and UX designers at Google, and its components enable a reliable development workflow to build beautiful and functional web projects. It has replaced react-mdl (which is now deprecated), already reaching nearly 7k stars.
Following the Ant Design specification, React Ant Design is a React UI library that contains a set of components and demos. It’s written in TypeScript with complete defined types, and provides an NPM+ webpack + dva front-end development workflow.
Semantic UI React is the official Semantic-UI-React integration. With nearly 5k stars and used by Netflix and Amazon, these components provide an interesting and flexible arsenal.
Onsen UI React Components made available with Onsen UI React bindings and provide hybrid mobile apps with React and Onsen UI Framework. With 81 contributors and over 5.6k stars it’s an interesting library to consider.
At nearly 8k stars, React Virtualized provides React components for efficiently rendering large lists and tabular data.
Individual components can be found in the popular awesome-react and awesome-react-components projects. Different components can also be grouped into a Scope on the Bit community hub to install and sync components between different repos and projects.
For more information and to build your web app. Hire React.js Developer from us, as we give you 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 app using React.js, please visit our technology page.
Content Source:
In a good Redux architecture, you are encouraged to keep your store state minimal, and derive data from the state as needed. As part of that process, we recommend that you use “selector functions” in your application, and use the Reselect library to help create those selectors. Here’s a depth detail of correct use of Reselect.
A “selector function” is simply any function that accepts the Redux store state (or part of the state) as an argument, and returns data that is based on that state. Selectors don’t have to be written using a special library, and it doesn’t matter whether you write them as arrow functions or the function
keyword. For example, these are all selectors:
const selectEntities = state => state.entities; function selectItemIds(state) { return state.items.map(item => item.id); } const selectSomeSpecificField = state => state.some.deeply.nested.field; function selectItemsWhoseNamesStartWith(items, namePrefix) { const filteredItems = items.filter(item => item.name.startsWith(namePrefix)); return filteredItems; }
You can call your selector functions whatever you want, but it’s common to prefix them with select
or get
, or end the name with Selector, like selectFoo
, getFoo
, or fooSelector
.
The first reason to use selector functions is for encapsulation and reusability.
The next reason to use selectors is to improve performance. Performance optimization generally involves doing work faster, or finding ways to do less work. For a React-Redux app, selectors can help us do less work in a couple different ways.
Let’s imagine that we have a component that requires a very expensive filtering/sorting/transformation step for the data it needs. To start with, its mapState
function looks like this:
const mapState = (state) => { const {someData} = state; const filteredData = expensiveFiltering(someData); const sortedData = expensiveSorting(filteredData); const transformedData = expensiveTransformation(sortedData); return {data : transformedData}; }
Right now, that expensive logic will re-run for every dispatched action that results in a state update, even if the store state that was changed was in a part of the state tree that this component doesn’t care about.
What we really want is to only re-run these expensive steps if state.someData
has actually changed. This is where the idea of “memoization” comes in.
Memoization is a form of caching. It involves tracking inputs to a function, and storing the inputs and the results for later reference. If a function is called with the same inputs as before, the function can skip doing the actual work, and return the same result it generated the last time it received those input values.
The Reselect library provides a way to create memoized selector functions. Reselect’s createSelector
function accepts one or more “input selector” functions, and an “output selector” function, and returns a new selector function for you to use.
const selectA = state => state.a; const selectB = state => state.b; const selectC = state => state.c; const selectABC = createSelector( [selectA, selectB, selectC], (a, b, c) => { // do something with a, b, and c, and return a result return a + b + c; } ); // Call the selector function and get a result const abc = selectABC(state); // could also be written as separate arguments, and works exactly the same const selectABC2 = createSelector( selectA, selectB, selectC, (a, b, c) => { // do something with a, b, and c, and return a result return a + b + c; } );
There’s a specific performance issue that can occur when you use memoized selectors with a component that can be rendered multiple times.
The React-Redux connect
function supports a special “factory function” syntax for mapState
and mapDispatch
functions, which can be used to create unique instances of selector functions for each component instance.
If the first call to a mapState
or mapDispatch
function returns a function instead of an object, connect
will use that returned function as the real mapState
or mapDispatch
function. This gives you the ability to create component-instance-specific selectors inside the closure:
const makeUniqueSelectorInstance = () => createSelector( [selectItems, selectItemId], (items, itemId) => items[itemId] ); const makeMapState = (state) => { const selectItemForThisComponent = makeUniqueSelectorInstance(); return function realMapState(state, ownProps) { const item = selectItemForThisComponent(state, ownProps.itemId); return {item}; } }; export default connect(makeMapState)(SomeComponent);
Both component 1 and component 2 will get their own unique copies of selectItemForThisComponent
, and each copy will get called with consistently repeatable inputs, allowing proper memoization.
Hire React.js Developer from us, as we give you 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 app using React.js, please visit our technology page.
Content Source:
Facebook is one of the world’s most powerful company and has created a framework called React.js for building web apps. React.js respectively appear to be in a battle for the future of the web, with the active online debate and adoption of large consumer-facing apps seeming to lean quite strongly in React.js’s favor at present.
React.js is getting so much popularity that it is unlikely to be replaced in the near future. React also embraces unidirectional data flows through Flux architecture. Stacks like Firebase are getting popular, thanks to React community.
Today, there are many updates that have been in the pipeline for the last few months are finally released. Among the updates are some long-standing feature requests, including fragments, error boundaries, portals, support for custom DOM attributes, improved server-side rendering, and reduced file size. There are few updates in React v16.0.0 as listed below.
Better error handling
Previously, run-time errors during rendering could put React in a broken state, producing cryptic error messages and requiring a page refresh to recover. To address this problem, React 16 uses a more resilient error-handling strategy.
Better server-side rendering
React 16 includes a completely rewritten server renderer. It’s really fast. It supports streaming, so you can start sending bytes to the client faster.
Portals
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
Support for custom DOM attributes
Instead of ignoring unrecognized HTML and SVG attributes, React will now pass them through to the DOM. This has the added benefit of allowing us to get rid of most of React’s attribute whitelist, resulting in reduced file sizes.
New core architecture
React 16 is the first version of React built on top of a new core architecture, codenamed “Fiber.” Fiber is responsible for most of the new features in React 16, like error boundaries and fragments.
Perhaps the most exciting area we’re working on is async rendering—a strategy for cooperatively scheduling rendering work by periodically yielding execution to the browser. The upshot is that, with async rendering, apps are more responsive because React avoids blocking the main thread.
In Conclusion, The future of ReactJS is very bright. You would have to check a few pages built properly on ReactJS to know the difference. The concepts of redux are being copied in mobile development as well.
Hire React.js Developer from us, as we give you 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 app 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