DEV Community

Cover image for Top  tips and tricks about react
chayan999
chayan999

Posted on

Top tips and tricks about react

React Hooks

Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components. It does not work inside classes.
Hooks are backward-compatible, which means it does not contain any breaking changes. Also, it does not replace your knowledge of React concepts.

When to use a Hooks

If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing function component.
If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing function component.

Rules of Hooks

Hooks are similar to JavaScript functions, but you need to follow these two rules when using them. Hooks rule ensures that all the stateful logic in a component is visible in its source code. These rules are:

  1. Only call Hooks at the top level Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at the top level of the React functions. This rule ensures that Hooks are called in the same order each time a components renders.
  2. Only call Hooks from React functions You cannot call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Hooks can also be called from custom Hooks. ##Hooks State Hook state is the new way of declaring a state in React app. Hook uses useState() functional component for setting and retrieving state. Let us understand Hook state with the following example.
import React, { useState } from 'react';  

function CountApp() {  
// Declare a new state variable, which we'll call "count"  
  const [count, setCount] = useState(0);  

  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={() => setCount(count + 1)}>  
        Click me  
      </button>  
    </div>  
  );  
}  
export default CountApp;  
import React, { useState } from 'react';  

function CountApp() {  
  // Declare a new state variable, which we'll call "count"  
  const [count, setCount] = useState(0);  

  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={() => setCount(count + 1)}>  
        Click me  
      </button>  
    </div>  
  );  
}  
export default CountApp;
Enter fullscreen mode Exit fullscreen mode

Hooks Effect

The Effect Hook allows us to perform side effects (an action) in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.
Side effects have common features which the most web applications need to perform, such as:

  • Updating the DOM,
  • Fetching and consuming data from a server API,
  • Setting up a subscription, etc.

JavaScript DOM Nodes

The Document Object Model, or DOM for short, is a platform and language independent model to represent the HTML or XML documents. It defines the logical structure of the documents and the way in which they can be accessed and manipulated by an application program.
In the DOM, all parts of the document, such as elements, attributes, text, etc. are organized in a hierarchical tree-like structure; similar to a family tree in real life that consists of parents and children. In DOM terminology these individual parts of the document are known as nodes.
The Document Object Model that represents HTML document is referred to as HTML DOM. Similarly, the DOM that represents the XML document is referred to as XML DOM.

Tip: The Document Object Model or DOM is, in fact, basically a representation of the various components of the browser and the current Web document (HTML or XML) that can be accessed or manipulated using a scripting language such as JavaScript.

Using Default Props

React supports the notion of defaultProps which you can think of as default function arguments. When you create an element and you did not include a prop with a default then React will substitute that prop with its corresponding value from defaultProps. Flow supports this notion as well. To type default props add a static defaultProps property to your class.

class Button extends React.Component {
  // ...
}

Button.defaultProps = {
  color: 'red'
};
If props.color is not provided, it will be set by default to 'red':
render() {
    return <Button /> ; // props.color will be set to red
  }
If props.color is set to null, it will remain null:
 render() {
    return <Button color={null} /> ; // props.color will remain null
  }
Enter fullscreen mode Exit fullscreen mode

Optimizing Performance

Performance is an important aspect when building webpages and applications. You need to understand how long your users interact with your app, how often they leave, and the response time as well.
The first 10 seconds are vital to determine if a user will leave or continue interacting with your web pages. You must clearly speed up the page, bring value within these 10 seconds, and get the user’s attention to spend more time on your page.
This is where optimizing your page and speeding up the response time becomes important to maintain a good user experience. Node.js is known to produce super-fast performing and scalable web applications. Node.js uses event-driven architecture and non-blocking (asynchronous) tasks that run on a single thread.

now I will highlight some point about optimising performance

  • Asynchronous
  • Synchronous
  • Query Optimization
  • Caching
  • Go Session Free
  • Script Tracing and Logging
  • Client-side Rendering
  • Avoid Memory Leaks
  • Keeping your Code Light and Compact ## State Management One of the biggest and most common problems in is state management. like me are constantly focused on keeping the state object in sync with its view and the DOM representation. Users can interact with the application in many ways and it’s a big task to provide a clean transition from one state to another. State exists in every application, even those made with plain JavaScript. It's not a concept specific to JS libraries; it's necessary to understand for any app you intend to make. Libraries use this concept of state within your applications for your own benefit. ## React’s tree reconciliation Reconciliation is the process through which React updates the DOM. When a component’s state changes, React has to calculate if it is necessary to update the DOM. It does this by creating a virtual DOM and comparing it with the current DOM. In this context, the virtual DOM will contain the new state of the component. Let’s build a simple component that adds two numbers. The numbers will be entered in an input field.
class App extends React.Component {

  state = {
    result: '',
    entry1: '',
    entry2: ''
  }

  handleEntry1 = (event) => {
    this.setState({entry1: event.target.value})
  }

    handleEntry2 = (event) => {
    this.setState({entry2: event.target.value})
  }

  handleAddition = (event) => {
    const firstInt = parseInt(this.state.entry1)
    const secondInt = parseInt(this.state.entry2)
    this.setState({result: firstInt + secondInt })
  }

  render() {
    const { entry1, entry2, result } = this.state
    return(
 <div>  
        <div>
          Result: { result }
        </div>
        <span><input type='text' onChange={this.handleEntry1} /></span>
        <br />
        <br />
        <span><input type='text' onChange={this.handleEntry2} /></span>
        <div>
          <button onClick={this.handleAddition} type='submit'>Add</button>
        </div>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
Enter fullscreen mode Exit fullscreen mode

First, we’ll need to set up the initial state for the fields, then update the state when a number is entered. The component will look like this:

render() {
    const { entry1, entry2, result } = this.state
    return(
      <div>  
        <div>
          <p>Entry 1: { entry1 }</p>
          <p>Entry 2: { entry2 }</p>
          <p>Result: { result }</p>
        </div>
        <br />
        <div>
          <span>Entry 1: </span>
          <input type='text' onChange={this.handleEntry1} />
        </div>
        <br />
        <div>
          <span>Entry 2: </span>
  <input type='text' onChange={this.handleEntry2} />
        </div>lass App extends React.Component {

  state = {
    result: '',
    entry1: '',
    entry2: ''
  }

  handleEntry1 = (event) => {
    this.setState({entry1: event.target.value})
  }

  handleEntry2 = (event) => {
    this.setState({entry2: event.target.value})
  }

  handleAddition = (event) => {
    const firstInt = parseInt(this.state.entry1)
    const secondInt = parseInt(this.state.entry2)
    this.setState({result: firstInt + secondInt })
  }

        <div>
          <button onClick={this.handleAddition} type='submit'>Add</button>
        </div>
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

When an entry is made in the first input field, React creates a new tree. The new tree which is the virtual DOM will contain the new state for entry1. Then, React compares the virtual DOM with the old DOM and, from the comparison, it figures out the difference between both DOMs and makes an update to only the part that is different. A new tree is created each time the state of App component changes — when a value is entered in either of the inputs field, or when the button is clicked.

ReactDOM.render

The render method can be called the primary gateway between React and the DOM.
Let’s say you have defined a React element (), as well as a DOM node to act as a container for that element (div with the ID of “container”). Now, you can use ReactDOM.render to render the element within that container using the syntax given below:
ReactDOM.render(<Calculator />, document.querySelector("#container"))

🔹 Note: If the Calculator component has already been mounted in the div element, calling this again will simply update the DOM based on the difference between the components.

Parameters:

  • React element
  • Selected DOM Node
  • Callback function (optional)

Note: ReactDOM.render requires a React element as the first argument. React elements are generated through React.createElement. Therefore, you may use that syntax or simply invoke a JSX interpretation of the component to get the parameters in the correct format for the arguments. Using React.createElement, our code can be modified to look like this:
ReactDOM.render(React.createElement(Calculator), document.querySelector("#container"))

Top comments (0)