Revisiting React

Rahul Biswas
6 min readMay 7, 2020

--

Day 4 of React Learning — Milestone 2 (Week 2)

Welcome to the 4th day of React learning. Today we will revisit our previous React concepts. We will discuss today briefly about - React Cheatsheet, React Best Practices 2020, Web Accessibility, React Higher-Order Components (HOC), React Component Lifecycle, and their methods. So, let’s get into the article.

1. React Cheatsheet

React remains a popular frontend library throughout all the years since it has been introduced. To be updated with the latest trends and crack the best out of React’s advantage, here are some awesome cheatsheet we must know.

i) Children props

This prop helps to pass a whole component as a prop, to other components. It’s a great advantage. We can save lots of work if a similar component’s layout style can be passed to other components.

Example:

ii) Fragments

Fragments are special components for displaying multiple components without adding an extra element to the DOM.
We can wrap the element inside <> … </> to use fragments

Syntax:

// if no ‘key’ is used as a prop
<>

</>

or

// if ‘key’ is used as a prop
<Fragment key={item.id}>

</Fragment>

Example:

iii) Condition with useEffect

useEffect lets us conditionally perform effects with the dependencies array. The dependencies array is the second argument, and if any values in the array changes, the effect function runs again.

Example:

iv) useContext

We can replace the use of multiple props all the times by useContext. useContext manages states very precisely and decrease the uses of props.

Example:

2. React Best Practices - 2020

There are lots of React best practices out there, but we have discussed to of them here -

i) Code Splitting React Route:

Splitting the code segment into multiple parts can precisely divide our React apps into multiple pieces which are definitely easy to understand. By code-splitting, our apps get “bundled”, which further can be loaded and used independently multiple at a time.

ii) DRY

DRY stands for Don’t Repeat Yourself, that means our code should be small and specific. We should not repeat our code where we can reuse the existing segment. It saves lots of time and opens a new way to use our code segment for future use as many times as we need.

Example:

Let’s say we want to add multiple buttons that contain icons, instead of adding the markup for each button, we can simply use the IconButton.

const buttons = ['facebook', 'twitter', 'youtube'];

return (
<div>
{
buttons.map( (button) => {
return (
<IconButton
onClick={doStuff( button )}
iconClass={button}
/>
);
} )
}
</div>
);

3. Web accessibility

A quotation from the inventor of the world wide web:

The power of the Web is in its universality.
Access by everyone regardless of disability is an essential aspect.

— Tim Berners-Lee

Web accessibility is the inclusive practice of ensuring there are no barriers that prevent interaction with, or access to, websites on the World Wide Web by people with physical disabilities, situational disabilities, and socio-economic restrictions on bandwidth and speed.

When sites are correctly designed, developed, and edited, generally all users have equal access to information and functionality.

Web accessibility of React:
React fully supports building accessible websites, often by using standard HTML techniques.

4. Accessible Forms

For an easily accessible and user-friendly form element, we need to focus on two things:

i) Labeling
Like HTML standard practice, we need to follow the leveling principles also in React (inside JSX)

Example:

in HTML - for
in JSX - htmlFor

<label htmlFor="namedInput">Name:</label><input id="namedInput" type="text" name="name"/>

ii) Notifying the user of errors
Errors should have to be notified so that they are understood by the users, that has been generated by the form element.

Some error notifications can be

Overall feedback
When a form is submitted, it is important that the user is notified whether the submission was successful or if errors occurred.

Overall feedback can be achieved by using -
i) the main heading,
ii) the page title
iii) dialogs and
iv) by listing errors

In-line feedback
This is more specific feedback at or near the form controls can better help users to use your form. This includes feedback to indicate correctly entered input as well as errors in the input.

In-line feedback can be achieved by using -
i) After submit,
ii) During typing and
iii) by On focus change

5. Higher-Order Components (HOC)

Higher-order components are functions that take a component and returns a new component.
This is an advanced technique in React for reusing component logic.

Example:

const EnhancedComponent = higherOrderComponent(WrappedComponent);

6. Composition for avoiding Mutation

Rather than mutating the original Higher Order Component (HOC), we can use Composition.
Mutating HOCs are a leaky abstraction - the consumer must know how they are implemented in order to avoid conflicts with other HOCs.

Example:

In the following example, the input component cannot be reused separately from the enhanced component. More crucially, if we apply another HOC to EnhancedComponent that also mutates componentDidUpdate, the first HOC’s functionality will be overridden! This HOC also won’t work with function components, which do not have lifecycle methods.

Instead of mutation, HOCs should use composition, by wrapping the input component in a container component:

This HOC has the same functionality as the mutating version while avoiding the potential for clashes. It works equally well with class and function components. And because it’s a pure function, it’s composable with other HOCs, or even with itself.

7. Component Lifecycle of React

Every React Component has a lifecycle of its own, the lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence.

Some commonly used lifecycle methods

i) for Mounting - constructor(), render(), componentDidMount()

ii) for Updating - render(), componentDidUpdate()

iii) for Unmounting - componentWillUnmount()

8. render()

The render() method is the only required method in a class component.

When called, it should examine this.props and this.state and return one of the following types:

React elements:
Typically created via JSX. For example, <div /> and <MyComponent /> are React elements that instruct React to render a DOM node, or another user-defined component, respectively.

Arrays and fragments:
Lets us return multiple elements from render.

Portals:
Lets us render children into a different DOM subtree.

String and numbers:
These are rendered as text nodes in the DOM.

Booleans or null:
Render nothing. (Mostly exists to support return test && <Child /> pattern, where test is boolean.)

9. componentDidMount()

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree).

Initialization that requires DOM nodes should go here. If we need to load data from a remote endpoint, this is a good place to instantiate the network request.

10. componentWillUnmount()

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. We can perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

We should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.

That’s all about today…Thanks for Reading. Happy Learning :)

--

--

Rahul Biswas

Love to work with Technologies, Web & obviously JavaScript.