DEV Community

Cover image for Demystifying 20 lesser-known React terms and features (With examples) ๐Ÿ”ฎ
Vaibhav Khulbe
Vaibhav Khulbe

Posted on • Updated on

Demystifying 20 lesser-known React terms and features (With examples) ๐Ÿ”ฎ

React has been around for more than 5 years now. Most of the companies and big brands like Facebook (the creator itself), Instagram, Twitter, Netflix, Whatsapp, Dropbox etc are using this UI library on their existing projects as stated in this Medium article by SPEC INDIA.

While learning more about React to dig deeper I got to know some unknown words used in the React ecosystem but used on a regular basis. What are they? How we use them? Here's a quick look at 20 lesser-known React features.


Mystery GIF

Let's answer each of them!

1. Is that a React element or a component? ยฌ_ยฌ

I was definitely confused when I just started with libraries with these.

> Element (Doc ๐Ÿ“ƒ)

An element describes what you want to see on the webpage. These are just plain objects which appear on your web application in terms of DOM nodes.

Example:

const element = <h1>Hello, world</h1>; // THIS IS AN ELEMENT
ReactDOM.render(element, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

> Component (Doc ๐Ÿ“ƒ)

A component, at it's base level is a JavaScript function which accept input(s) called props and return elements.

Example:

const LoginButton = ({ onLogin }) => 
    <div id={'login-btn'} onClick={onLogin}>Login</div>
Enter fullscreen mode Exit fullscreen mode

Elements are what components are โ€œmade ofโ€.

2. What's a SyntheticEvent? (Doc ๐Ÿ“ƒ) ^_~

Whenever you use event handling all of that handling logic is a passed instance of SyntheticEvent which is like a wrapper around the browser's native event. Internally, it forms part of React's Event System.

Example:

3. What are key props? (Doc ๐Ÿ“ƒ) >:(

A key is a special string attribute which is recommended to use when creating arrays of elements. This is so that React is able to identify which element has changed, added or removed. These give elements in the array their own identity.

Example:

const ItemList = item.map((item) =>
  <li key={item.id}>
    {item.title}
  </li>
)
Enter fullscreen mode Exit fullscreen mode

4. What are refs and why we use them? (Doc ๐Ÿ“ƒ) ;[

A ref is an attribute which is used to return a reference to an element. And as for why we use them, the answer is most us don't I guess ๐ŸŒ. Okay, they can be useful when you directly need to access the DOM element or an instance of a component. Try to avoid it and replace its use case with state lifting.

Example:

// Reference: https://css-tricks.com/working-with-refs-in-react/#article-header-id-1
class Example extends React.Component {
  constructor(props) {
    super(props)
    // Create the ref
    this.exampleRef = React.createRef()
  }
  render() {
    return (
      <div>
        // Call the ref with the `ref` attribute
        <input type="text" ref={this.exampleRef} />
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

5. Why it's recommended to use callback refs over findDOMNode()? ~_~

First, the difference between the two:

> Callback refs (Doc ๐Ÿ“ƒ)

This gives much better control over when refs are set and unset. Instead of passing an attribute, we pass a function here. The function receives the React component instance or HTML DOM element as its argument, which can be used elsewhere in the application.

Example:

// Reference: https://css-tricks.com/working-with-refs-in-react/#article-header-id-2 
<input type="text" ref={element => this.textInput = element} />
Enter fullscreen mode Exit fullscreen mode

> findDOMNode() (Doc ๐Ÿ“ƒ)

This method is useful for reading values of DOM like an input field value. It's also used to measure DOM performance.

Example:

ReactDOM.findDOMNode(component);
Enter fullscreen mode Exit fullscreen mode

The documentation says (in bold):

In most cases, you can attach a ref to the DOM node and avoid using findDOMNode at all. findDOMNode is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. It has been deprecated in StrictMode.

6. What is React Fiber? O_O

The GitHub repo tells all about it in detail:

GitHub logo acdlite / react-fiber-architecture

A description of React's new core algorithm, React Fiber

React Fiber Architecture

Introduction

React Fiber is an ongoing reimplementation of React's core algorithm. It is the culmination of over two years of research by the React team.

The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

Other key features include the ability to pause, abort, or reuse work as new updates come in; the ability to assign priority to different types of updates; and new concurrency primitives.

About this document

Fiber introduces several novel concepts that are difficult to grok solely by looking at code. This document began as a collection of notes I took as I followed along with Fiber's implementation in the React project. As it grew, I realized it may be a helpful resource for othersโ€ฆ

7. What are controlled and uncontrolled components? :-]

> Controlled components (Doc ๐Ÿ“ƒ)

This is a component that controls input elements within the forms on user input successive user input(s). It means every state change will have its associated handler function.

Example:

handleChange(event) {
  this.setState({value: event.target.value.toLowerCase()})
}
Enter fullscreen mode Exit fullscreen mode

> Uncontrolled components (Doc ๐Ÿ“ƒ)

These type of components store their own state internally. In an input form field, the update information is reflected without React to do anything. It has a catch though, now you can't force the field to have a certain value.

Example:

class UserProfile extends React.Component {
  constructor(props) {
    super(props)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.input = React.createRef()
  }
  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value)
    event.preventDefault()
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          {'Name:'}
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

8. What's the difference between createElement and cloneElement? ^_+

> createElement (Doc ๐Ÿ“ƒ)

All the JSX you write is converted to use this React method. It simply creates and returns a new React element of the given type.

Example:

class Hello extends React.Component {
  render() {
    return React.createElement('div', null, `Hello ${this.props.toWhat}`);
  }
}
ReactDOM.render(
  React.createElement(Hello, {toWhat: 'World'}, null),
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

> cloneElement (Doc ๐Ÿ“ƒ)

It's simply used to clone and return a new element. It's similar to the following JSX:

<element.type {...element.props} {...props}>{children}</element.type>
Enter fullscreen mode Exit fullscreen mode

Example:

// Reference: https://www.educative.io/edpresso/what-is-the-react-cloneelement-function
class ParentComp extends React.Component {
  render() {
    // The new prop to the added.
    let newProp = 'red';
      // Looping over the parent's entire children,
      // cloning each child, adding a new prop.
    return (
      <div>
        {React.Children.map(this.props.children,
          child => {
            return React.cloneElement(child,
            {newProp}, null);
        })}
      </div>
    )
  }
}
// The child component
class MyButton extends React.Component {
  render() {
    return <button style =
    {{ color: this.props.newProp }}>
    Hello World!</button>
  }
}
Enter fullscreen mode Exit fullscreen mode

9. How to create a prop proxy for a Higher Order Component (HOC)? :|

A prop proxy helps to add or edit props passed to the component.

Example:

function HOC(WrappedComponent) {
  return class Test extends Component {
    render() {
      const newProps = {
        title: 'New Header',
        footer: false,
        showFeatureX: false,
        showFeatureY: true
      };
      return <WrappedComponent {...this.props} {...newProps} />
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

10. What's the Context (Doc ๐Ÿ“ƒ)? ^_+

Context is a way to pass any data through the component tree of your application. They are used so that the data isn't passed manually at every level of the app. There's an entire page dedicated in the docs for Context from when to use them to some of its cons.

Example:

const {Provider, Consumer} = React.createContext(defaultValue);
Enter fullscreen mode Exit fullscreen mode

11. What is reconciliation? :|

Let's say your component's state changed, what React does in the background is that it compares the newly returned element to the one it previously rendered. If they're not equal, DOM updation is done. This entire process is called reconciliation.

12. What are React Portals (Doc ๐Ÿ“ƒ)? -.-

It is a way to render children into DOM node which exits outside the DOM hierarchy of the parent component in the app.

Example:

// Reference: https://blog.logrocket.com/learn-react-portals-by-example/
import { useEffect } from "react";
import { createPortal } from "react-dom";

const Portal = ({children}) => {
  const mount = document.getElementById("portal-root");
  const el = document.createElement("div");
  useEffect(() => {
    mount.appendChild(el);
    return () => mount.removeChild(el);
  }, [el, mount]);
  return createPortal(children, el)
};

export default Portal;
Enter fullscreen mode Exit fullscreen mode

13. What is ReactDOMServer (Doc ๐Ÿ“ƒ)? _

Typically used on a Node server, this is an object which enables you to render components to static markup for Server-Side Rendering (SSR).

Example:

// Using Express
import { renderToString } from 'react-dom/server'
import MyPage from './MyPage'

app.get('/', (req, res) => {
  res.write('<!DOCTYPE html><html><head><title>My Page</title></head><body>')
  res.write('<div id="content">')
  res.write(renderToString(<MyPage/>))
  res.write('</div></body></html>')
  res.end()
})
Enter fullscreen mode Exit fullscreen mode

14. What are decorators? =[

Decorators modify your component's functionality in a more flexible and readable way. The example below shows how you can use class decorators in React and read the process behind it in this Medium article:

Example:

@setTitle('Profile')
class Profile extends React.Component {
    //....
}
const setTitle = (title) => (WrappedComponent) => {
  return class extends React.Component {
    componentDidMount() {
      document.title = title
    }
    render() {
      return <WrappedComponent {...this.props} />
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

15. How to implement SSR? 8-)

Server-Side Rendering renders the React components on the server. The output is HTML content. You use [ReactDOMServer.](https://reactjs.org/docs/react-dom-server.html)

It output the regular HTML as a string, which can be then placed inside a page body as part of the server response. On the client-side, React detects the pre-rendered content and seamlessly picks up where it left off. Check out this article to implement SSR in React.

Example:

import ReactDOMServer from 'react-dom/server'
import App from './App'

ReactDOMServer.renderToString(<App />)
Enter fullscreen mode Exit fullscreen mode

16. What is a strict mode (Doc ๐Ÿ“ƒ)? =_=

It is a component which is used to detect potential problems in your application. This will not render any DOM element but activates checks and warnings for the descendants.
One thing to note is that the checks are run in development mode only and they do not impact the production build.

Example:

import React from 'react'

function ExampleApplication() {
  return (
    <div>
      <Header />
      <React.StrictMode>
        <div>
         // Strict mode applies to the following two components only
          <ComponentOne />
          <ComponentTwo />
        </div>
      </React.StrictMode>
      <Footer />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

17. What are mixins (Doc ๐Ÿ“ƒ)? >.<

If you want to separate components to have common functionality, you use mixins. According to the docs, mixins aren't recommended and can be replaced by HOCs.

Example:

const PureRenderMixin = require('react-addons-pure-render-mixin')

const Button = React.createClass({
  mixins: [PureRenderMixin],
  // ...
})
Enter fullscreen mode Exit fullscreen mode

18. What is a prototype array with shape? -_-

If you want to pass an array of objects to a component having a particular shape, you use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf(). Know more in the following Stackoverflow thread:

315

Is there a built-in way to use proptypes to ensure that an array of objects being passed to a component is actually an array of objects of a specific shape?

Maybe something like this?

annotationRanges: PropTypes.array(PropTypes.shape({
    start: PropTypes.number.isRequired,
    end: PropTypes.number.isRequired,
})),

Am I missing something super obvious here? Seems likeโ€ฆ

19. How to use https in create-react-app? :]

Head over to package.json file and modify the scripts section as:

"scripts": {
  "start": "set HTTPS=true && react-scripts start"
}
Enter fullscreen mode Exit fullscreen mode

20. How to find the current React version? ^_-

React has a method called React.version which you can add as a constant and use it anywhere to display the React version being used at runtime.

Example:

const REACT_VERSION = React.version

ReactDOM.render(
  <div>{`React version: ${REACT_VERSION}`}</div>,
  document.getElementById('app')
)
Enter fullscreen mode Exit fullscreen mode

I hope I've explained them in the right way. Did you know about them? Honestly, I never knew what mixins are in React!

Broken code? Check out our debugging in @VisualStudio docs: https://t.co/nvE0ygt7fF

Image source: https://t.co/NsWs0PcXio#DevHumour #Debugging #Programmer pic.twitter.com/nEbczhhwdm

โ€” Microsoft Developer UK (@msdevUK) April 8, 2020

๐Ÿ“ซ Subscribe to my weekly developer newsletter ๐Ÿ“ซ

PS: From this year, I've decided to write here on DEV Community. Previously, I wrote on Medium. If anyone wants to take a look at my articles, here's my Medium profile.

Latest comments (4)

Collapse
 
rammyblog profile image
Onasanya Tunde

Great job

Collapse
 
vaibhavkhulbe profile image
Vaibhav Khulbe

Thank you!

Collapse
 
iarmankhan profile image
Arman Khan

Greate article Vaibhav! Learned something new today. Also you inspire me alot to write great articles just like you.๐Ÿ’ฅ๐Ÿ’ฅ

Collapse
 
vaibhavkhulbe profile image
Vaibhav Khulbe

Thank you Arman for the compliment! ๐Ÿ˜„