Should You Use React for Your Next Website? – CloudSavvy IT

React logo on a dark background

React has surged in popularity in recent years. Described as “a JavaScript library for building user interfaces,� React’s declarative approach to rendering simplifies the construction of complex UIs.

React is a versatile tool with a broad range of applications, ranging from traditional websites to complex web apps. There’s no clear line that defines when you should use React. Instead, there’s guideline indicators which can help you assess whether React could be a good fit.

Look for Components

One sign that a site might benefit from React is if you’re planning to reuse a large number of self-contained components. Abstract interface elements such as form controls and data display cards are prime candidates for conversion to React components. This is especially true if your components are likely to incorporate custom behavior beyond what the browser provides.

React’s very nature encourages you to isolate reusable aspects of your interface into individual components. Components are typically defined within their own source files, making your codebase easier to navigate and organize.

import React from "react";
import ReactDOM from "react-dom";
 
class ChildComponent extends React.Component {
 
    render() {
        return <h2>Child Component</h2>;
    }
 
}
 
class DemoComponent extends React.Component {
 
    render() {
        return (
            <div>
                <h1>Demo Component</h1>
                <ChildComponent />
            </div>
        );
    }
 
}
 
ReactDOM.render(<DemoComponent />, document.body);

Screenshot of React components

Components can include other components to enable rapid construction of complex UIs. A single component might render some UI, apply custom CSS styles and handle JavaScript-based user interactions. React utilizes a custom templating language, JSX, to enable you to construct componentized UIs in a style that’s similar to regular HTML.

Find Stateful Sections

React excels at managing areas of your interface that render differently depending on the value of some internal state. The idea of “state� might seem vague at first. However, it’s easy to identify stateful sections of your site – they’re normally areas that produce changes within the UI.

Examples include the value of a form input, whether a toggle button is selected, and the loading status of dynamically loaded content. Content itself is often delivered “statefully� – a generic blog post screen will display the article data stored in the component’s inner state.

In the example below, the text on the screen is determined by the value of the demo key in the component’s state. The text is changed automatically every five seconds by updating the state.

import React from "react";
import ReactDOM from "react-dom";
 
class DemoComponent extends React.Component {
 
    constructor(props) {
        super(props);
 
        this.state = {
 
            demo: 1
 
        };
 
        this.timer = null;
 
        this.updateText = this.updateText.bind(this);
 
    }
 
    componentDidMount() {
        this.timer = setInterval(this.updateText, 5000);
    }
 
    componentWillUnmount() {
        if (this.timer) clearInterval(this.timer);
    }
 
    updateText() {
        this.setState({demo: (this.state.demo + 1)})
    }
 
    render() {
        return <h1>{this.state.demo}</h1>;
    }
 
}
 
ReactDOM.render(<DemoComponent />, document.body);

Screenshot of React components

Try to find areas of your website which need to change dynamically. This might be as a consequence of a user action, a recurring timer or a browser event (like going offline or fetching new background data).

Any stateful section that updates regularly is likely to benefit from using React. React’s seamless state management provides a single source of truth for your site’s business logic.

Identify Interactivity

React can make it simpler to handle interactivity within your website. The library abstracts JavaScript’s built-in event handlers to provide a unified interface for responding to user interactions.

Using React can be particularly advantageous in the case of complex forms. Its approach, based on “controlled components�, ensures the form’s internal state matches what the user sees in the UI.

import React from "react";
import ReactDOM from "react-dom";
 
class DemoComponent extends React.Component {
 
    constructor(props) {
        super(props);
 
        this.state = {
 
            value: "I'm a text field"
 
        };
 
        this.updateValue = this.updateValue.bind(this);
 
    }
 
    updateValue(e) {
        this.setState({value: e.target.value});
    }
 
    render() {
        return <input onChange={this.updateValue} value={this.state.value} />;
    }
 
}
 
ReactDOM.render(<DemoComponent />, document.body);

Screenshot of React components

By attaching event handlers to form controls, you can update a component’s state whenever the user changes the control’s value – such as by typing in a text field or selecting an option from a dropdown menu. Then, make the control’s value prop (which maps to the HTML value attribute) refer back to the component’s state. Changes in the UI and the component will now be reflected in each other.

Look for DOM Manipulation

This is the golden rule to consider when deciding whether to use React. Stateful content, user interactivity and dynamically updating components all feed back into the DOM. Direct DOM manipulation using the browser’s JavaScript APIs is clumsy at best and nightmarishly unwieldy at worst.

Any aspect of your website which requires extensive manipulation of the DOM – that’s the HTML elements displayed on the page – is a probable source of complexity. React can greatly simplify these scenarios. Its component-based nature abstracts away the tedium of injecting HTML and managing event bindings.

Because React is declarative, you define what the DOM should look like within a component’s render() method. The library then does the hard work of creating, removing and shuffling HTML elements to produce the DOM structure you’ve “declared�.

Internally, React maintains its own “virtual DOM� which ensures this whole procedure runs performantly. This allows the library to perform the smallest number of re-renders possible, minimising the overheads normally associated with DOM manipulation.

Conclusion

React’s popularity derives from the significant simplification of state management and DOM manipulation which it provides. Its declarative nature allows highly complex web applications to be constructed in a similar manner to basic HTML pages, with developers only needing to define what the DOM structure should look like at the current point in time.

As with any good thing, there are also downsides. Using React will increase the download size of your website. It also adds a reliance on JavaScript which could prevent some users from accessing your content. There are many more failure points than a “pure� HTML, CSS and JavaScript solution.

These limitations mean React may not be the best choice for simple static websites. Sites with little interactivity and limited DOM manipulation tend to be better off sticking with a lighterweight solution. React’s benefits really begin to pay off on sites which possess considerable internal state. React brings improvements to developer productivity, codebase maintainability, and overall site performance when used carefully on data-centric interactive sites.

Source link

The post Should You Use React for Your Next Website? – CloudSavvy IT appeared first on TechFans.

Share