React — Advanced Useful Concepts

Krina Soni
6 min readMay 25, 2019

React has come up with new advanced features and solutions to the existing problems.

Last year, they announced all of the features in React Conf 2018. Also, detailed documentation is on their website.
Here you can watch the React Conf 2018.

We’ll cover few points with examples which are useful to solve few problems created by react itself.
I have also made a Github Repository for all the examples.

  • React Fragments
  • Stateless Components
  • Stateful Components
  • Hooks
  • redux-form Integration

Let’t start by creating application through create-react-app — Modern build setup. If you’re unaware of this, go through this.

create-react-app advanced-react
cd advanced-react
npm start
npm install react-router-dom redux redux-form redux-logger @material-ui/core — save

This will generate app named advanced-react, and install dependencies which we will use and integrate.

create-react-app will give you simple structure, we will make it more simpler in application way. Our structure will look like below.

advanced-react/
README.md
package.json
public/
index.html
favicon.ico
src/
components
Home
home
counter
counter_hooks
About
about
banner
Contact
contactUs
images
common
header
redux
actions
reducers
store
App.css
App.js
routes.js
App.test.js
index.css
index.js

Stateless Components

Stateless component — A functional component is just a plain javascript function which takes props as an argument and returns a react element.

Basically, It does not have any state. You may create react component like this while you have to render conditional based on props.
You may also call this as Pure components as it doesn’t modifies anything just renders based on some condition.

Example,

import React from ‘react’;function Banner(props) {
return (
<div className={props.imageClass}>
<h5 style={{ fontSize: ‘20px’ }}>I am FullStack Developer</h5>
<p>Let’s code together!!</p>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</div>
)
}
export default Banner;

Fragments

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

While we break components and use as child components, there comes a time when you need to use parent tag to bind all html and logic. It may generate unnecessary divs in DOM tree.

Solution is Fragments which can be used with it’s syntax and also you can pass key to it.

<React.Fragment>
<h2>{props.title}</h2>
<Counter />
<CounterHooks />
</ React.Fragment>

We’ll not have to use extra divs to bind number of child components and it will work flawlessly.

Hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

While they come up with hooks, you do not need to change any existing logic or concepts of react about props, state, context, refs and events.
Hooks just provide direct API to use all of these concepts.

Before we start learning new concept —why should we need to learn this.

  • Reusing stateful component logic
  • Class components

We can not re-use a stateful component and if we try to use it then code becomes cumbersome at some point. And if we try to look our application components in devTools then you’ll find so much wrapping of Higher order components, Providers, and other components.
It’s much of a Wrapper Hell.

Hooks allow you to reuse stateful logic without changing your component hierarchy.

To work in React, you need to understand classes, this, super, and other many concepts of JavaScript and manage it through out the component through lifecycle methods.

Hooks let you use more of React’s features without classes.

Now, Let’s go through different types of hooks provided by React.

useState is a hook to use local state in a functional components.

React will preserve the state in between re-renders. It comes with a argument for initial state and returns Current State and function to update it.
(Somewhat like this.setState from previous versions.)
You can use multiple states through useState and initialise it using any primitive type.

import React, { useState } from 'react';export default function CounterHooks() {
const [counter, updateCounter] = useState(0);

return (
<div>
<p>This counter is build through React Hooks</p>
<span>You clicked {counter} times</span>
<button onClick={() => { updateCounter(counter + 1) }} >Click here</button>
</div>
)
}

useEffect provides the ability to perform side effects from a function component.

It provides the same functionality as lifecycle methods — componentDidMount, componentShouldUpdate and componentWillUnmount for classes into functional components.
React runs the effects after every render and they have access to its props and state as it is defined in component.

We usually use componentDidMount to fetch data through third-party API.
Let’s take example of same to fetch from API and store values and map through each and display the list.

import React, { useEffect, useState } from “react”;
import List from ‘@material-ui/core/List’;
import ListItem from ‘@material-ui/core/ListItem’;
import ListItemAvatar from ‘@material-ui/core/ListItemAvatar’;
import ListItemText from ‘@material-ui/core/ListItemText’;
import Avatar from ‘@material-ui/core/Avatar’;
export default function PostList() {
// Initialize post state
const [posts, setPosts] = useState([]);
useEffect(async () => {
const res = await fetch(
“https://www.reddit.com/r/reactjs.json"
);
const json = await res.json();
// Store the posts into state
setPosts(json.data.children.map(c => c.data));
}, [setPosts]);
return (
<div>
{posts.map(post => (
<List key={post.id}>
<ListItem>
<ListItemAvatar>
<Avatar>
{‘P’}
</Avatar>
</ListItemAvatar>
<ListItemText primary={post.title} secondary= {post.author} />
</ListItem>
</List>
))}
</div>
);
}

Now, If we want to use these hooks, there are some rules to follow.

You can only call hooks at Top Level

You can only call hooks from React functions

You can call hooks from custom hooks, not Javascript functions.

React provides eslint hooks plugin to make sure that we follow these rules.

React provides other basic hooks as well as useRef ,useContext, useReducer, useLayoutEffect and so on.

Redux-form Integration

Why redux-form ? What it provides? How to use?

Let’s go through each one by one officially.
redux-form provides you,

Decorator which wraps form with higher order component and accessibility to props.
Maintain form state and dispatched actions in redux.
Various Action Creators for interacting with your forms throughout the application.

We can integrate it by adding formReducer in reducer and combine it with all application reducers.
Wrap component/form in Higher-order component as

ContactUsForm = reduxForm({
form: 'contact'
})(ContactUsForm);

redux-form provides Field component, Fields for multiple, various types of validation.
Example,

import React, { Component } from ‘react’;
import { Field, reduxForm } from ‘redux-form’;
import TextField from ‘@material-ui/core/TextField’;
import Button from ‘@material-ui/core/Button’;
const renderTextField = ({
label,
input,
meta: { touched, invalid, error },
…custom
}) => (
<TextField
label={label}
placeholder={label}
error={touched && invalid}
helperText={touched && error}
{…input}
{…custom}
/>)
const validate = values => {
const errors = {}
const requiredFields = [‘firstName’,‘lastName’,‘email’,]
requiredFields.forEach(field => {
if (!values[field]) {
errors[field] = ‘Required’
}
})
if (values.email && !/^[A-Z0–9._%+-]+@[A-Z0–9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = ‘Invalid email address’
}
return errors
}
class ContactUs extends Component {
constructor(props) {
super(props);
this.state = {
}
}
_callContact = (values) => {
console.log(‘values’, values)
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this._callContact)}>
<div>
<label htmlFor=”firstName”>First Name</label>
<Field name=”firstName” component={renderTextField} type=”text” />
</div>
<div>
<label htmlFor=”lastName”>Last Name</label>
<Field name=”lastName” component={renderTextField} type=”text” />
</div>
<div>
<label htmlFor=”email”>Email</label>
<Field name=”email” component={renderTextField} type=”email” />
</div>
<Button variant=”outlined” color=”primary” type=”submit”>Submit</Button>
</form>
)
}
}
const createReduxForm = reduxForm({
form: ‘contact’,
validate
})
ContactUs = createReduxForm(ContactUs);
export default ContactUs;

Find all documentation here.

To manage all of the values, validation and component wrapping logic, use developer tools which they officially provide — React Dev Tools

Add it to your browser and run this and you will be able to watch all of the activities.

Reviews/Suggestion are most welcome. :)
Clap if you find it useful.

--

--

Krina Soni

Passionate about places, photos and coding! Food is love !!