Demystifying 20 lesser-known React terms and features (With examples) 🔮
Tags: javascript, react, webdev, programming
Published: 2020-04-12 13:39:51


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](https://medium.com/front-end-weekly/top-25-companies-brands-using-reactjs-development-8be87b32cec2) 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](https://media.giphy.com/media/dgEtXsuqq2PL2/giphy.gif)
<figcaption>Let's answer each of them!</figcaption>

---

## 1. Is that a React element or a component? ¬_¬

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

#### > Element ([Doc 📃](https://reactjs.org/docs/rendering-elements.html))
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:_

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

#### > Component ([Doc 📃](https://reactjs.org/docs/components-and-props.html))
A component, at it's base level is a JavaScript function which accept input(s) called _props_ and return elements.

_Example:_

```jsx
const LoginButton = ({ onLogin }) => 
    <div id={'login-btn'} onClick={onLogin}>Login</div>
```

> Elements are what components are “made of”.

## 2. What's a `SyntheticEvent`? ([Doc 📃](https://reactjs.org/docs/events.html)) ^_~

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](https://reactjs.org/docs/handling-events.html). 

_Example:_

{% codepen https://codepen.io/syohansson/pen/bBgEBm default-tab=js %}


## 3. What are _key_ props? ([Doc 📃](https://reactjs.org/docs/lists-and-keys.html#keys)) >:(

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:_

```jsx
const ItemList = item.map((item) =>
  <li key={item.id}>
    {item.title}
  </li>
)
``` 

## 4. What are _refs_ and why we use them? ([Doc 📃](https://reactjs.org/docs/glossary.html#refs)) ;[

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](https://reactjs.org/docs/lifting-state-up.html).

_Example:_

```jsx
// 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>
    )
  }
}
```

## 5. Why it's recommended to use _callback refs_ over `findDOMNode()`? ~_~

First, the difference between the two:

#### > Callback refs ([Doc 📃](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs))

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:_

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

#### > `findDOMNode()` ([Doc 📃](https://reactjs.org/docs/react-dom.html#finddomnode))

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

_Example:_

```jsx
ReactDOM.findDOMNode(component);
```
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](https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage).

## 6. What is React Fiber? O_O

The GitHub repo tells all about it in detail:

{% github acdlite/react-fiber-architecture %}

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

#### > Controlled components ([Doc 📃](https://reactjs.org/docs/forms.html#controlled-components))

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:_

```jsx
handleChange(event) {
  this.setState({value: event.target.value.toLowerCase()})
}
```

#### > Uncontrolled components ([Doc 📃](https://reactjs.org/docs/uncontrolled-components.html))

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:_

```jsx
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>
    );
  }
}
``` 

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

#### > `createElement` ([Doc 📃](https://reactjs.org/docs/react-api.html#createelement))

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:_

```jsx
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')
);
```

#### > `cloneElement` ([Doc 📃](https://reactjs.org/docs/react-api.html#cloneelement))

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

```jsx
<element.type {...element.props} {...props}>{children}</element.type>
```

_Example:_

```jsx
// 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>
  }
}
```

## 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:_

```jsx
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} />
    }
  }
}
```

## 10. What's the Context ([Doc 📃](https://reactjs.org/docs/context.html))? ^_+

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:_

```jsx
const {Provider, Consumer} = React.createContext(defaultValue);
```

## 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 📃](https://reactjs.org/docs/portals.html))? -.-

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

_Example:_

```jsx
// 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;
```

## 13. What is ReactDOMServer ([Doc 📃](https://reactjs.org/docs/react-dom-server.html))? *_*

Typically used on a Node server, this is an object which enables you to render components to static markup for [Server-Side Rendering (SSR)](https://alligator.io/react/server-side-rendering/).

_Example:_

```jsx
// 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()
})
```

## 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:

{% medium https://medium.com/@gigobyte/enhancing-react-components-with-decorators-441320e8606a %}

_Example:_

```jsx
@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} />
    }
  }
}
```

## 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](https://www.freecodecamp.org/news/server-side-rendering-your-react-app-in-three-simple-steps-7a82b95db82e/) to implement SSR in React.

_Example:_

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

ReactDOMServer.renderToString(<App />)
```

## 16. What is a strict mode ([Doc 📃](https://reactjs.org/docs/strict-mode.html))? =_=

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:_

```jsx
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>
  )
}
``` 

## 17. What are mixins ([Doc 📃](https://reactjs.org/docs/react-without-es6.html#mixins))? >.<

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:_

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

const Button = React.createClass({
  mixins: [PureRenderMixin],
  // ...
})
```

## 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:

{% stackoverflow 32325912 %}

## 19. How to use `https` in _create-react-app_? :]

Head over to _package.json_ file and modify the `scripts` section as:

```json
"scripts": {
  "start": "set HTTPS=true && react-scripts start"
}
```

## 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:_

```jsx
const REACT_VERSION = React.version

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

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

<blockquote class="twitter-tweet" data-partner="tweetdeck"><p lang="en" dir="ltr">Broken code? Check out our debugging in <a href="https://twitter.com/VisualStudio?ref_src=twsrc%5Etfw">@VisualStudio</a> docs: <a href="https://t.co/nvE0ygt7fF">https://t.co/nvE0ygt7fF</a><br><br>Image source: <a href="https://t.co/NsWs0PcXio">https://t.co/NsWs0PcXio</a><a href="https://twitter.com/hashtag/DevHumour?src=hash&amp;ref_src=twsrc%5Etfw">#DevHumour</a> <a href="https://twitter.com/hashtag/Debugging?src=hash&amp;ref_src=twsrc%5Etfw">#Debugging</a> <a href="https://twitter.com/hashtag/Programmer?src=hash&amp;ref_src=twsrc%5Etfw">#Programmer</a> <a href="https://t.co/nEbczhhwdm">pic.twitter.com/nEbczhhwdm</a></p>&mdash; Microsoft Developer UK (@msdevUK) <a href="https://twitter.com/msdevUK/status/1247922154785648641?ref_src=twsrc%5Etfw">April 8, 2020</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

---

#### [📫 Subscribe to my weekly developer newsletter 📫](https://mailchi.mp/f59beeac6b9b/devupdates)

##### 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](https://medium.com/@vaibhavkhulbe)'s my Medium profile.