DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for How To React.js?
Sujesh Gathe
Sujesh Gathe

Posted on

How To React.js?

In this article, we would put our heads together about all the things you need to understand to master React.js. And why react is the future of front-end development. React developers are in great demand since it is used by Yandex, Netflix, Facebook, and many more well-known businesses.
We would be discussing about all the fundaments of react.js and what technologies and tools are available in react for implementing it into our front-end design.

React Basics

Front-end is the part of the web that is displayed to the user, responsible for sending data and making requests to the back-end side, also called the server-side.
Here are some basics you should know about react to begin with your web app development.

  1. Components You may split the user interface using React components so that each component can be reused and handled separately. Or, to put it another way, any application you create with React will be built up of what are known as components. Using components makes creating user interfaces considerably simpler. You may view a user interface (UI) divided into several separate parts, or components, and work on them individually before merging them all into a parent component to create your final UI. A React component can be either β€œstateful” or β€œstateless.” β€œStateful” components are of the class type, while β€œstateless” components are of the function type.

Example of Stateless Component

import React from 'react';
//an example of function type component
const ExampleComponent = (props) => {
    return ( <h1>Welcome to Educative!</h1>);
}

export default class App extends React.Component {
  render() {
    //rendering ExampleComponent component in App Component
    return (
      <div>
        <ExampleComponent/> 
        </div>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

The stateless component named ExampleComponent is added into the component in the example above. The only element in the ExampleComponent is the h1.

Example for Stateful Component

import React from 'react';

//an example of class type component
class ExampleComponent extends React.Component {

        constructor(props) {
            super(props);

            this.state = {
                heading: "This is an Example Component!"
            }


        }

        render() {
            return ( 
                <div>
                    <h1 > {this.props.welcomeMsg} < /h1> 
                    <h2 > { this.state.heading} < /h2> 
                </div>);

        }

}

export default class App extends React.Component {
  render() {
    const welcomeMsg="Welcome to Educative!";
    return (
      <div>
        <ExampleComponent welcomeMsg={welcomeMsg}/>
      </div>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

The stateful component named ExampleComponent is added into the component in the example above.

  1. Props
    React components receive parameters called Props. HTML attributes are used to pass props to components. React’s data flow between components is uni-directional (from parent to child only).
    Props are an optional input, and can be used to send data to the component. They are read-only since they are immutable attributes. They are useful for displaying fixed values as a result of this.

  2. States
    State, a unique built-in object in React, enables components to produce and manage their own data. Contrary to props, components cannot generate or maintain state internally, although they can pass data with state.
    State should not be modified directly, but it can be modified with a special method called setState( ).

Example

this.state.id = β€œ2020”; // wrong

this.setState({         // correct  
    id: "2020"
});

Enter fullscreen mode Exit fullscreen mode
  1. JSX
    JSX is Referred as JavaScript XML. We can write HTML in React thanks to JSX. React's use of JSX makes adding and writing HTML simpler. It is a JavaScript syntactic enhancement. It should be used with React to specify how the user interface should appear. Although JSX may resemble a template language, it has all of JavaScript's capabilities.

  2. Events
    React has the ability to take action in response to user events, much as HTML DOM events. The same HTML eventsβ€”click, change, mouseover, etc.β€”are available in React.
    Event handlers determine what action is to be taken whenever an event is fired. This could be a button click or a change in a text input. Essentially, event handlers are what make it possible for users to interact with your React app. Handling events with React elements is similar to handling events on DOM elements, with a few minor exceptions.

  3. Conditional Rendering
    React allows us to build many components that each have the required behavior. Then, based on a few factors or the status of our application, we may render them. In other words, a component chooses which components it will return depending on one or more circumstances. The same way that JavaScript's conditions function in React, conditional rendering does as well. The elements that reflect the current state are created using JavaScript operators, and React Component updates the UI to match them.
    Example of conditional rendering, Consider the following component that only renders a warning button if a warning message is passed as props.

function Warning (props) {
 const {warningMessage} = props
 if (!warningMessage) {
 return null
 }
 return (
 <>
 <button>Warning</button>
 </>
 )
}
Enter fullscreen mode Exit fullscreen mode

Now, if you pass in β€˜warning_Message’ to the component, a warning button will be rendered. However, if you don’t, will return null and the button will not be displayed.

<Warning warning_Message="Warning message"/> // the warning button is rendered
<Warning/> // the warning button is not rendered
Enter fullscreen mode Exit fullscreen mode

React UI frameworks

  1. Material UI
    Material UI is the best and most preferred library among the front-end developers. To develop a user interface in our React apps, we can simply import and use several components from the Material-UI package. As a result, the developers may save a lot of time by not having to create everything from start. It's using an MIT License, so it's free even for commercial use. It uses the same license as React. See
    Material UI provides us Various in built Templets, components, icons, APIs, etc to enhance our web app. thus makes it easy for a developer, its just like buying or borrowing any component for our project rather than building it from scratch. for more info check

  2. Ant Design
    The Experience Technology Department of Ant Financial has developed Ant Design, a design language for middleware that aims to standardize user interface requirements for middleware projects, cut down on unnecessary implementation and design costs, and free up resources for design and front-end development. It is the second most popular UI for React developers, It is a Enterprise-class UI with a set of high-quality react components specially designed for web applications


You could require data flow solutions like Redux or MobX while developing actual projects.

3.Chakra UI
You may create React apps using the Chakra UI component toolkit, which is straightforward, flexible, and user-friendly. Chakra UI helps us build innovative features for our web app. To implement most trending feature we use Chakra UI, Light and Dark UI. Chakra is extremely time-efficient, has excellent accessibility defaults, is well-designed and documented, and looks fantastic right out of the box. If you need more information about Chakra UI,Discord channel for Chakra

4.React Bootstrap
To construct responsive, component-based UI components, ReactJS Bootstrap was designed as a front-end toolkit component library. As a substitute for JavaScript Bootstrap, it provides easily accessible, dynamic, and easy-to-integrate components to speed up our development process. JQuery is used by Javascript Bootstrap to power the interface of its components. Because Javascript Bootstrap directly manipulates the Document Object Model (DOM), it is in opposition to ReactJS' declarative methodology. There have been instances when ReactJS projects have used Javascript Bootstrap, but their support components have only used basic Vanilla Bootstrap stylesheets and have not used JQuery. Hence, React developers developed their component library that follows the Virtual DOM concept and does not involve JQuery.

Important Hooks

In React 16.8, hooks are a brand-new feature. They provide state and other React capabilities without the need for class creation.

1.useState
We can keep track of the state in a function component with the React useState Hook.
By executing useState in our function component, we initialize our state. UseState returns two values after accepting an initial state:

  • The current State
  • Function that updates the current state Example
import { useState } from "react";

function FavoriteColor() {
  const [color, setColor] = useState("");
}

Enter fullscreen mode Exit fullscreen mode

2.useEffect
You may instruct React that your component needs to do an action after rendering by using this Hook. React will keep track of the function you gave (which we'll refer to as our "effect") and run it once the DOM adjustments have been made.

3.UseRef
Between renderings, you may maintain values using the useRef Hook. It may be used to hold a changeable value that, when altered, doesn't require a new rendering. It may be applied to directly access a DOM element.

4.UseContext
Utilizing the context is primarily intended to provide your components access to certain global data and to re-render when that global data is modified. When you have to pass along props from parents to kids, context solves the props drilling problem.

5.UseReducer
Two parameters are accepted by the useReducer Hook. Your own state logic is included in the reducer function, and initialState can either be a simple value or, more often than not, an object. The dispatch method and the current state are returned by the useReducer Hook.
Redux should be used in applications that have several features. With these features sharing chunks of the same information. While using the useContext and useReducer, the Redux functionalities can be reproduced.

6.UseCallback
The useCallback hook is utilized when a component's child is rendering it repeatedly without a reason. Pass an array of dependencies together with an inline callback. In the event that one of the dependencies has changed, useCallback will only return a memoized version of the callback.

State Management Tools

Developers may check the application's state using state management to make sure that modifications reflect the business processes and real-world context in the right way.
The tools used for State management in react are

1.Redux
Redux is a design pattern and framework that uses "actions," or events, to manage and update application state. With rules guaranteeing that the state may only be altered in a predictable manner, it acts as a central repository for state that must be utilized across the whole program. It is one of the most commonly used tool by full-stack developers.

How Redux works

Redux can be used for any application that places a high priority on the ability to predictably store states. It should be clear that Redux can be used for the client side (frontend) with user interfaces.

2.Mobx
A straightforward, scalable, and state management solution without boilerplate is MobX. The code is decoupled, portable, and most importantly, simple to test because it is possible to maintain application state independently of any UI framework. It uses the publish/subscribe design paradigm to implement observable data.
Redux outperforms MobX in terms of popularity, scalability, and the development community. However, MobX could be your best option if you want to get up to speed quickly and create straightforward apps with minimal boilerplate code.

3.Hookstate
The declarative React useState concept is extended with new functionality by the Hookstate package and is wrapped in a global version. Its main characteristics include: A plugin system to enhance the library's functionality with state validation and persistency. State management in TypeScript is supported by Hookstate by default.

React.JS Packages

This files are a kind of manifest file for your application. This file plays a very important role in the react application development and deployment. In short, we can say, Package.json = Metadata associated with project + All Dependencies with version + scripts.
Some of the most useful package that you should be familiar with are
1.React Router
React router is a common library for routing in React. It permits switching between views of different React Application components, permits changing the browser URL, and keeps the UI in sync with the URL.
React router can be an overkill for certain projects where all you need is basic navigation and routing functionalities. In that context, React Router is not necessary at all. Learn how react hooks can replace react routers

2.Axios
One of the most commonly used package now a days to built efficient and user-friendly application. It is a popular library mainly used to send asynchronous HTTP requests to REST endpoints.
Axios for API handling
Axios is a Javascript library that implements the Promise API that is native to JS ES6 and is used to make HTTP requests using node.js or XMLHttpRequests from the browser. It allows client-side XSRF protection and may be used to intercept HTTP requests and answers. Additionally, it can cancel requests.

3.React Query
React Query is frequently referred to as React's missing data-fetching library. However, it simplifies the process of retrieving, caching, syncing, and updating server data in your React apps in a more technical sense.
Facebook uses React Query for small parts of its main page. There are some apps built fully with React.
As React Query's fetching mechanisms are agnostically built on Promises, you can use React Query with literally any asynchronous data fetching client, including GraphQL!

4.Storybook
A development environment for UI components is called Storybook.
You may use it to explore a library of components, see each component's many states, and design and test components in real time.
By separating components, it accelerates and simplifies development. This enables you to focus on one element at once. Without having to launch a complicated development stack, force specific data into your database, or use your application's navigation, you may create full user interfaces.


This are the most fundamental tools and technologies used now a days for front-end development. Thus to be a successful front-end developer using react.js you must be familiar using this technologies. I hope this article was able to provide proper guidance to endure react.js expertise.

Top comments (7)

Collapse
 
fjones profile image
FJones

You've explained hooks, but you show class components for stateful components. Hooks require function components and make them stateful despite still being function components. Hence why the most used hook is useState.

I think a separate heading explaining function components (and a paragraph somewhere explaining pure components, excuse me if I missed it) would do wonders here, as well as of course rewriting the first heading not to make it seem as though stateful components need to be class components.

Collapse
 
sujeshgathe profile image
Sujesh Gathe Author

Thank you @fjones for the feedback, I would definitely keep this thing in mind for my next blog

Collapse
 
efpage profile image
Eckehard

Hy Sujesh,

very nice writeup and thank you for trying to explain things as simpe as possible.

We should mention, that react is a world on itΒ΄s own. There are other approaches like Angular or Vue, and if you decide, to go with one of them, there will be no way to use features of the other. React is a world on its own, but on a closed island.

For professionals, the world of react deliveres a complete workflow, and lotΒ΄s of great tools. But for a newbie there is pretty much to learn. Each tool you mentioned will have a pile of documentation to read, and sometimes you will find documentation for a previous version, that is not valid anymore. Learning React on your own is a hard work.

Beside that, you will at least have to learn the usage of:

  • html
  • CSS
  • Javascript
  • DOM
  • SQL

Not all of the things you will find can be easily understood, as some approaches have been grown out of somewhere in the dark history of the internet, they miss a basic concept and can only be understood, if you look to the history they came from.

So, before you start to learn REACT, you should look around and try to get a good overview about newer or alternative approaches.

Best regards, Eckehard

Collapse
 
mezieb profile image
Okoro chimezie bright

Nice workπŸ‘

Collapse
 
luisjasperusa profile image
Luis Jasper

Nice article

Collapse
 
sujeshgathe profile image
Sujesh Gathe Author

Thank you

Collapse
 
sarkariprep profile image
Sarkariprep

Wow Nice Thank u Sir Mp Rojgar Nirman

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await