The Definitive React Hooks Cheatsheet

The Definitive React Hooks Cheatsheet

<strong>React Hooks is the new hotness in the React world. I'm writing steadily more and more of them and I thought it would be useful to have a cheatsheet to refer back to which encompasses the basic hooks as well as the intricacies of useEffect. Check out the official Hooks API Reference for more in-depth information.</strong>

React Hooks is the new hotness in the React world. I'm writing steadily more and more of them and I thought it would be useful to have a cheatsheet to refer back to which encompasses the basic hooks as well as the intricacies of useEffect. Check out the official Hooks API Reference for more in-depth information.

Table of Contents

useEffect (for lifecycle methods)

useEffect, among other things, allows you to write your own side effects and trigger a re-render when needed.

But to make it simpler, useEffect also substitutes lifecycle methods. Let’s talk about them.

substitute for componentDidUpdate + componentDidMount

When does it run? On every render

What’s the catch? It’s not just a componentDidUpdate replacement, it also runs on mount. So it’s not 1-to-1

Important features? useEffect can take in a 2nd argument, you have to skip that argument. You can also return a function, we’ll cover that in the next section.

Code sandbox playground: Go play with it

Syntax:

import { useEffect } from 'react';

useEffect(() => {
// whatever runs here will run on each re-render
});

substitute for componentDidMount + componentWillUnmount

When does it run? On component mount and unmount

What’s the catch? The syntax is very close to the previous use case. It threw me off several times but it makes sense once you read the docs. If the effect runs more than once, make sure you passed in the 2nd argument

Important features? This is an effect that runs only once. The mount logic goes in the body of the effect function, the unmount/cleanup logic goes into a function that you return from the effect.

Code sandbox playground: Go play with it

Syntax:

import { useEffect } from 'react';

useEffect(() => {
// run mount logic here such as fetching some data

return () => {
// unmount logic goes here
};
}, []); // note the empty array

You can leave either the mount or unmount logic empty to work only off one of those lifecycle substitute. Meaning that:

  1. leave mount logic empty so that only unmount logic runs (substitute for just componentWillUnmount)
  2. return nothing so that only mount logic runs (substitute for just componentDidMount)
useEffect for side effects

useEffect's primary goal is to encompass any side effect you might want to use. A side effect is essentially something that you do within your component which affects the world at large. Whether that’s a network request, setting the document title, or what have you.

Run when necessary

When does it run? when the component re-renders, useEffect will check dependencies. If the dependency values changed, useEffect will run the effect

What’s the catch? React does a shallow comparison. If you use an object or an array that you mutate, React will think nothing changed.

Important features useEffect skips running the effect when things don’t change. You don’t actually have to use the dependency values in the effect. You can pass in a prop value as a dependency.

Code sandbox playground: Go play with it

Syntax:

import { useEffect } from 'react';

function SomeComponent(props) {
useEffect(() => {
// logic runs only when dependency variables changed
}, [arrOfDependency, values, props.id]); // array of values to check if they've changed
}

Potential use cases

Since the hook is more difficult to explain, I’d like to offer a list of use cases

  1. run a side effect (like a fetch) when a prop changes to get new data
  2. run a resource-heavy calculation only when the calculation values change
  3. update the page (like document title) when a value updates
useState

State is probably the reason why people switch from stateless (functional) components to class components. useState allows us to have stateful components without classes.

What does it return? Current state and a function that lets you set state

What’s the catch? The state setting function will replace the previous state with the new one rather than merging them as class state would have. You need to merge your objects yourself before setting the state.

Important features You can use as many useState hooks in your component as you want. Passing any value to useState will create the initial state. It’s also a convention to not call the variables state and setState but rather by contextual names (eg. user and setUser). useState accepts any value for state, it doesn’t have to be an object.

Code Sandbox playground: Check out the useState examples

Syntax:

import { useState } from 'react';

// setup
const defaultValue = { name: "Antonin" };
const [state, setState] = useState(defaultValue);

// scenario 1 usage
// resulting state only contains key user with value 'antjanus'
setState({ user: 'antjanus' });

// scenario 2 usage
// resulting state contains key name with value 'A. Januska'
setState({ name: 'A. Januska' });

// scenario 3 usage
// resulting state is a merger between { name: 'A. Januska' } and { user: 'antjanus'}
setState({ ...state, user: 'antjanus'});

useReducer

useReducer is an alternative to useState and if you’ve used Redux in the past, this will look familiar.

What are the arguments? What does it return? useReducer takes in a reducer function and the initialState. It returns the current state and a dispatcher (sound familiar?)

How does it run? On state change, dispatch an object with a type and a data payload (read about flux standard action for more info). The reducer we passed into useReducer will receive the current state and the dispatched object. It returns the new state.

What’s the catch? It’s a more complicated workflow but it works just like you’d expect if you’ve used Redux.

Important features The reducer gets run on every dispatch. It gets access to the previous state. useReducer also includes a 3rd argument you can use to create the initial state

Code Sandbox playground: Check out the useReducer example

Syntax

import { useReducer } from 'react';

function reducer(currentState, action) {
switch(action.type) {
// handle each action type and how it affects the current state here
}
}

function SomeComponent() {
const [state, dispatch] = useReducer(reducer, initialState);

dispatch({ type: 'ADD', payload: data }); // { type: 'ADD', payload: data } gets passed into the reducer as the action argument while state gets passed in as the currentState argument
}

Building Your Own Hooks

A quick note on building your own hooks. It’s as easy as using the existing hooks and composing them together inside of a function that starts with use. Here’s a quick example of a useUser hook.

What are the requirements? That the function starts with the keyword use. Eg. useUser or useSomethingElse.

Important features: you can call any hooks within your custom hook and it works as expected.

Code Sandbox playground: Check out the custom hooks example

Syntax:

import { useEffect } from 'react';

function useUser(userId) {
let [user, setUser] = useState(null);

useEffect(() => {
fetch(/api/user/${userId})
.then(data => data.toJSON())
.then(data => setUser(data));
}, [userId]);

return user;
}

function SomeComponent(props) {
const user = useUser(props.id);
}

What about the rest?

There are other hooks you can use such as useMemouseCallback and so on. I would say that those are more advanced hooks and if you understand the basic hooks, go ahead and check out the official docs.

I also understand there are some advanced usage examples for many of these (like passing useReducer’s dispatch down several levels).

If you find something incorrect or some extra information useful that isn’t included, let me know! And I’ll include it!

Originally published by Antonin Januska at https://dev.to/antjanus/the-definitive-react-hooks-cheatsheet-2ebn

Follow great articles on Twitter

Learn More

☞ Modern React with Redux

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ The Complete React Web Developer Course (2nd Edition)

☞ Node with React: Fullstack Web Development

☞ Beginner Full Stack Web Development: HTML, CSS, React & Node

☞ React JS and Redux - Mastering Web Apps

☞ React 16 - The Complete Guide (incl. React Router 4 & Redux)

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

React Web Development: A Guide to Develop Progressive Web Applications

React Web Development: A Guide to Develop Progressive Web Applications

Outperform your competition with progressive web development and React.

Progressive web applications (PWAs) quickly gained popularity because they are web performance applications based on fast performance, streamlined to provide a mobile app-like experience. PWAs are built using HTML, CSS, and JavaScript to create a level of availability and performance equivalent to that of native mobile applications. They respond quickly, consume less data, store more space, and support push notifications and offline use in the browser.

Building a progressive web application has now become the web development trend that every business wants to follow. Significant players like Twitter and Flipboard have recently rolled out their progressive web apps to provide a mobile experience for users, without requiring them to install the app. In this article, you will learn how to build a progressive web application using React. Let's get started.

Step One — Set up the React Application

First, create a React application with create-react-app. To do so, you need to run the following commands:

  • npm install -g create-react-app
  • create-react-app pwa-app

Now, install React Router:

You need to replace the content of src / App.js using the code below to get a basic template with navigation.

import React, { Component } from 'react';
import { Router, browserHistory, Route, Link } from 'react-router';
import './App.css';

const NavBar = () => (
<div className="navbar">
<Link to="/">Feed</Link>
<Link to="/profile">Profile</Link>
</div>
);

const Template = ({ title }) => (
<div>
<NavBar />
<p className="page-info">
This is the {title} page.
</p>
</div>
);

const Feed = (props) => (
<Template title="Feed"/>
);

const Profile = (props) => (
<Template title="Profile"/>
);

class App extends Component {
render() {
return (
<Router history={browserHistory}>
<Route path="/" component={Feed}/>
<Route path="/profile" component={Profile}/>
</Router>
);
}
}
export default App;

Now, you'll have to update the default styles by replacing your src/App.css with the styles below to make your application look clean.

.navbar {
background-color: #01C8E5;
text-align: center;
}

.navbar a {
display: inline-block;
padding: 10px;
color: #fff;
text-decoration: none;
}

.page-info {
text-align: center;
font-weight: bold;
}

Then, run npm start to test the application in the browser. It is basically an application with two routes. Now, you will convert it to PWA.

Step Two — Lighthouse Setting and Auditing

Lighthouse is an automated open-source tool for testing applications against PWA checklists. It facilitates audits for accessibility, performance, and more.

Check your application with Lighthouse. Click the Lighthouse icon from the top right corner in Chrome and then click the "Create Report" button. The generated report will look like this:

Creating a report to test your PWA with Lighthouse

Fix all failed audits.

Step 3 — Sign Up for a Service Staff

Service employees are proxy servers that connect the application and the network. With Service Worker, you will have to block network requests and save cached files. It allows your application to work even with an unavailable system.

Create an empty worker.js file in your application's general directory and add the following code to that file.

// Flag for enabling cache in production
var doCache = false;

var CACHE_NAME = 'pwa-app-cache';

// Delete old caches
self.addEventListener('activate', event => {
const currentCachelist = [CACHE_NAME];
event.waitUntil(
caches.keys()
.then(keyList =>
Promise.all(keyList.map(key => {
if (!currentCachelist.includes(key)) {
return caches.delete(key);
}
}))
)
);
});

// This triggers when user starts the app
self.addEventListener('install', function(event) {
if (doCache) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
fetch('asset-manifest.json')
.then(response => {
response.json();
})
.then(assets => {
// We will cache initial page and the main.js
// We could also cache assets like CSS and images
const urlsToCache = [
'/',
assets['main.js']
];
cache.addAll(urlsToCache);
})
})
);
}
});

// Here we intercept request and serve up the matching files
self.addEventListener('fetch', function(event) {
if (doCache) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
});

Now, check if the browsers support service staff and then register worker.js. To do this, you need to add the following script to the file public/index.html (note that shrink-to-fit=no in the viewport meta tag has been deleted).

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('worker.js').then(function(registration) {
console.log('Worker registration successful', registration.scope);
}, function(err) {
console.log('Worker registration failed', err);
}).catch(function(err) {
console.log(err);
});
});
} else {
console.log('Service Worker is not supported by browser.');
}
</script>
</body>
</html>

You must restart your application and reload the browser after which you will see the Successful registration of member workers on the developer console. Now, recreate the Lighthouse report.

Step 4 - Improve the Progressive Nature of the Application

Your application will display an original blank div until the JavaScript loads and React hooks the original route. You must make sure your application works without downloading JS and displaying a bit of CSS and HTML before React takes effect. Your updated Index.html will look like this:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.navbar {
background-color: #01C8E5;
text-align: center;
}
.navbar a {
display: inline-block;
padding: 10px;
color: #fff;
text-decoration: none;
}
.page-info {
text-align: center;
font-weight: bold;
}
</style>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root">
<div class="navbar">
<a href="/">Feed</a>
</div>
<p class="page-info">
Loading an awesome app...
</p>
</div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('worker.js').then(function(registration) {
console.log('Worker registration successful', registration.scope);
}, function(err) {
console.log('Worker registration failed', err);
}).catch(function(err) {
console.log(err);
});
});
} else {
console.log('Service Worker is not supported by browser.');
}
</script>
</body>
</html>

Now, use Lighthouse to retest your application, and you'll see an improvement in the performance of the application.

Step 5 - Add the Splash Icon

You are required to add a 512x512 icon to display on the screen. To do so, you will have to update the manifest.json file and add the t0 icon to the public directory.

{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

Also, use the following meta tags to allow the browser to determine that your application is a PWA.

<!-- Tell the browser it's a PWA -->
<meta name="mobile-web-app-capable" content="yes">
<!-- Tell iOS it's a PWA -->
<meta name="apple-mobile-web-app-capable" content="yes">
Step 6 — Implement PWA

Now, only HTTPS is missing, and the cache can be fixed after you deploy the application. Update the doCache flag with true in the worker.js file. Create a new project in the firebase dashboard and name it "Pwa Application." Then, run the following command in the project directory:

npm install -g firebase-tools
firebase login
firebase init

Your Firebase.json will look like this:

{
"hosting": {
"public": "build",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}

After initializing, building and deploying your application.

  • npm run build
  • firebase deploy

You will see results after you test the application using Lighthouse on the deployed URL.

Final product with Lighthouse

Finally, you have created your first progressive web application with React.js!

Originally published by Manoj Kumar Bardhan at  dzone.com

=======================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Understanding TypeScript

☞ Typescript Masterclass & FREE E-Book

☞ React - The Complete Guide (incl Hooks, React Router, Redux)

☞ Modern React with Redux [2019 Update]

☞ The Complete React Developer Course (w/ Hooks and Redux)

☞ React JS Web Development - The Essentials Bootcamp

☞ React JS, Angular & Vue JS - Quickstart & Comparison

☞ The Complete React Js & Redux Course - Build Modern Web Apps

☞ React JS and Redux Bootcamp - Master React Web Development


ReactJS Development Company in Canada| Hire React JS Developers

a successful and trustworthy ReactJS development company in Ontario, Canada with presence in India. Hire our professional React JS developer who will guarantee you the custom ReactJS development and create bug-free, creative, seamless and interactive user interface apps. Get our services at the most competitive prices.