Wednesday, March 18, 2020

20 Essential React Tools for 2020

20 Essential React Tools for 2020

The React ecosystem has evolved into a growing list of dev tools and libraries. The plethora of tools is a true testament to its popularity. For devs, it can be a dizzying exercise to navigate this maze that changes at neck-breaking speed. To help navigate your course, below is a list of essential React tools for 2020.

Hooks

Hooks are a new addition to React as of version 16.8. They unlock useful features in classless components. With Hooks, React no longer needs lifecycle methods such as componentDidMount to manage state. This encourages separation of concerns because components are not managing their own state. Putting a lot of state management inside class components blows up complexity. This makes stateful components harder to maintain. Hooks attempt to alleviate this problem by providing key features.

The following basic Hooks are available:

  • useState: for mutating state in a classless component without lifecycle methods
  • useEffect: for executing functions post-render, useful for firing Ajax requests
  • useContext: for switching component context data, even outside component props

Pros:

  • mitigates state management complexity
  • supports functional components
  • encourages separation of concerns

Cons:

  • context data switching can exponentiate cognitive load

Functional Components

Functional components are a declarative way to create JSX markup without class components. They embrace the functional paradigm because they don’t manage state in lifecycle methods. This emphasizes focus on the UI markup without much logic. Because the component relies on props it becomes easier to test. Props have a one-to-one relationship with the rendered output.

This is what a functional component looks like in React:

const SimpleComponent = ({isInit, data}) =>
<>
  {useEffect(() => {!isInt && loadAjaxData()})}
  {data}
</>

Pros:

  • focuses on the UI only
  • testable component
  • less cognitive load when thinking about the component

Cons:

  • no lifecycle methods

Create React App

The quintessential tool to fire up a new React project. This manages all React dependencies via a single npm package. No more dealing with Babel, webpack, and whatnot. The entire dependency tool chain gets upgraded with react-scripts in package.json. There’s a way to integrate Create React App with any server-side rendering tool out there. The tool outputs index.html and static assets in the public folder. This public folder is the touch point where static assets are ready for integration.

It’s easy to get started:

npx create-react-app my-killer-app

And it's even easier to upgrade later:

npm i react-scripts@latest

Pros:

  • easy to get started
  • easy to upgrade
  • single meta-dependency

Cons:

  • no server-side rendering, but allows for integration

Proxy Server

Starting from version react-scripts@0.2.3 or higher, it’s possible to proxy API requests. This allows the back-end API and local Create React App project to co-exist. From the client side, making a request to /my-killer-api/get-data routes the request through the proxy server. This seamless integration works both in local dev and post-build. If local dev runs on port localhost:3000, then API requests go through the proxy server. Once you deploy static assets, then it goes through whatever back end hosts these assets.

To set a proxy server in package.json:

"proxy": "http://localhost/my-killer-api-base-url"

If the back-end API is hosted with a relative path, set the home page:

"homepage": "/relative-path"

Pros:

  • seamless integration with back-end API
  • eliminates CORS issues
  • easy set up

Con

  • might need a server-side proxy layer with multiple APIs

PropTypes

Declares the type intended for the React component and documents its intent. This shows a warning in local dev if the types don’t match. It supports all JavaScript primitives such as bool, number, and string. It can document which props are required via isRequired.

For example:

import PropTypes;

MyComponent.propTypes = {
  boolProperty: PropTypes.bool,
  numberProperty: PropTypes.number,
  requiredProperty: PropTypes.string.isRequired
};

Pros:

  • documents component’s intent
  • shows warnings in local dev
  • supports all JavaScript primitives

Cons:

  • no compile type checking

TypeScript

JavaScript that scales for React projects with compile type checking. This supports all React libraries and tools with type declarations. It’s a superset of JavaScript, so it’s possible to opt out of the type checker. This both documents intent and fails the build when it doesn’t match. In Create React App projects, turn it on by passing in --template typescript. TypeScript support is available starting from version react-script@2.1.0.

To declare a prop type:

interface MyComponentProps {
  boolProp?: boolean; // optional
  numberProp?: number; // optional
  requiredProp: string;
}

Pros:

  • compile type checking
  • supports all React tools and libraries, including Create React App
  • nice way to up your JavaScript skills

Cons:

  • has a learning curve, but opt out is possible

Redux

Predictable state management container for JavaScript apps. This tool comes with a store that manages state data. State mutation is only possible via a dispatch message. The message object contains a type that signals to the reducer which mutation to fire. The recommendation is to keep everything in the app in a single store. Redux supports multiple reducers in a single store. Reducers have a one-to-one relationship between input parameters and output state. This makes reducers pure functions.

A typical reducer that mutates state might look like this:

const simpleReducer = (state = {}, action) => {
  switch (action.type) {
    case 'SIMPLE_UPDATE_DATA':
      return {...state, data: action.payload};

    default:
      return state;
  }
};

Pros:

  • predictable state management
  • multiple reducers in a single store
  • reducers are pure functions

Cons:

  • set up from scratch can be a bit painful

React-Redux

Official React bindings for Redux, it comes in two main modules: Provider and connect. The Provider is a React component with a store prop. This prop is how a single store hooks up to the JSX markup. The connect function takes in two parameters: mapStateToProps, and mapDispatchToProps. This is where state management from Redux ties into component props. As state mutates, or dispatches fire, bindings take care of setting state in React.

This is how a connect might look:

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

const mapStateToProps = (state) => state.simple;
const mapDispatchToProps = (dispatch) =>
  bindActionCreators({() => ({type: 'SIMPLE_UPDATE_DATA'})}, dispatch);

connect(mapStateToProps, mapDispatchToProps)(SimpleComponent);

Pros:

  • official React bindings for Redux
  • binds with JSX markup
  • connects components to a single store

Cons:

  • learning curve is somewhat steep

Redux-Thunk

Thunk middleware for Redux to make asynchronous API calls. It defers execution behind a thunk to unlock asynchrony. A thunk is a function that defers evaluation. For example, () => 1 + 1, because it doesn’t have immediate execution. This comes with niceties, like access to store state, and dispatch. Optional parameters are also supported in the thunk.

For example:

const loadData = () => async (dispatch, getState, optionalAsyncTool) => {
  const state = getState();

  const response = await optionalAsyncTool.get('/url/' + state.data);
  dispatch({type: 'SIMPLE_LOAD_DATA', payload: response.data});
};

Pros:

  • quintessential tool for asynchrony
  • access to state, and dispatch
  • configurable with optional parameter

Cons:

  • at first, usefulness is not super clear

Redux-Logger

Logger for Redux that captures any dispatches going through the store. Each dispatch shows in the dev console in a log message. It allows drilling into prev, and next state. The action in the dispatch is also available for payload inspection. This logger is useful in local dev and can be ripped out post-build.

The following is a potential setup in Redux middleware:

import { createStore } from 'redux';

let middleware = [];

if (process.env.NODE_ENV === 'development') { // rip out post-build
  const {logger} = require('redux-logger');
  middleware.push(logger);
}

export default () => createStore({}, applyMiddleware(...middleware));

Pros:

  • good Redux insight
  • captures all dispatches in the store
  • can run in local dev only

Cons:

  • tricky to filter out unwanted messages

The post 20 Essential React Tools for 2020 appeared first on SitePoint.


by Camilo Reyes via SitePoint

15 Easy-to-Use Tools & Services to Improve Your Workflow

This sponsored article was created by our content partner, BAW Media. Thank you for supporting the partners who make SitePoint possible.

There's no lack of tools and services out there that you could put to use to improve your products or your business. Also, to increase your productivity, or save you time and money.

It's quite the opposite in fact. There are so many that finding one or more that will satisfy your most urgent needs can be a problem in itself. Some of the tools you use or services you subscribe to today may have served you well, but there's no guarantee they will continue to do so.

The very nature of web design demands that you keep up with the latest trends to stay abreast or keep a step ahead of the competition. That often requires finding new tools or services that will enable you to do so.

We hope this list of top tools and services for 2020 will serve to help you stay on top of your game and increase your productivity as well.

The post 15 Easy-to-Use Tools & Services to Improve Your Workflow appeared first on SitePoint.


by SitePoint Sponsors via SitePoint

CSS 'X', plus tips for improving site accessibility.

#432 — March 18, 2020

Read on the Web

Frontend Focus

'CSS X' — The CSS Versioning Debate — Remember the recent debate around CSS versioning and whether we should have a ‘CSS 4’ for marketing reasons? Here’s a good account from the W3C of just how CSS feature releases have worked up until this point. This piece also asks about the motives behind defining CSS versions for developers: How would it be defined in a useful way? How often should a new version be defined? And who could even define it?

Bert Bos (W3C)

16 Things to Improve Your Website Accessibility — Ensuring your sites are equally available to all is irrefutably the moral and right-minded approach to development (and it’s increasingly also a legal requirement too). Here, Bruce runs through over a dozen accessibility matters that you can address including technical, design and copywriting issues.

Bruce Lawson

Check-Off Implementing Checkout with Square — Easily start taking payments from your site with Square’s secure & customizable payments form. Get started today.

Square sponsor

A Complete Guide to calc() in CSS — CSS has a special calc() function for doing basic math — here, Chris Coyier runs through “just about everything there is to know” about it. A detailed guide with plenty of code snippet examples.

CSS Tricks

▶  The CSS Podcast — 001: The Box Model — A new podcast from the Chrome Developers team all about CSS. In the first episode Una Kravets and Adam Argyle discuss the CSS box model.

Google podcast

Happy 31st Birthday, World Wide Web — The web turned 31 last week, a good reason to revisit Tim Berners-Lee’s original proposal for the Web.

Coralie Mercier

“The goal of the Web is to serve humanity. We build it now so that those who come to it later will be able to create things that we cannot ourselves imagine.”

Sir Tim Berners Lee, computer scientist and inventor of the World Wide Web.

💻 Jobs

Find a Dev Job Through Vettery — Vettery is completely free for job seekers. Make a profile, name your salary, and connect with hiring managers from top employers.

Vettery

UX/Frontend Engineer @ Siteline — Join the founding engineering team at Siteline and help us revolutionize the payments process for construction.

Siteline

ℹ️ Interested in running a job listing in Frontend Focus? There's more info here.

📙 News, Tutorials & Opinion

CSS :nth-of-class Selector — This isn’t a real selector, but Bram Van Damme looks at some possible shortcomings with nth-child, leading to the conclusion that maybe we do need something like :nth-of-class.

Bram Van Damme

New Media Queries You Need to Know — A look through some of the most interesting new media queries in the Media Query Level 5 spec, and how to use them.

Kristofer Selbekk

Learning CSS Box Alignment — A comprehensive look at concepts in box alignment in CSS, which are useful for learning both Flexbox and Grid.

Ahmad Shadeed

The Problem with 'Snackbars' and What to Use Instead — Snackbars (those little ‘toast’ notification messages) are a popular way to inform users about something they just did, but Adam thinks they can cause lots of problems for users. Here he explains why that is and what to use instead.

Adam Silver

Animate CSS and SVGs with AnimeJS — AnimeJS is a JavaScript animation library with various features like SVG morphing animations and CSS animations. Here’s a look at how to use it.

Developer Bacon

How to Use CSS Scroll Snap — A straightforward tutorial showing how to add a scroll to your page without having to rely on JavaScript libraries.

Nada Rifki

Register for the Free ForwardJS May 2020 Livestream

ForwardJS sponsor

Building a Node.js Tool to Compare Google Lighthouse Reports

Luke Harrison

Here's How HTML Microdata Helps With Accessibility

Scott Vinkle

   ðŸ—“ Upcoming Events

Demystifying PWAs, March 25 — Webinar — In this free online session Lee Warrick will offer an introduction to PWAs and show you what you need to know to start building one.

PerfMatters, March 31 - April 1 — Online — A web performance conference, which has now moved to be a virtual event, with a focus on frontend web performance with talks by internationally renowned performance developers.

FrontCon, April 1-3 — Riga, Latvia — This event has been postponed until further notice due to the Coronavirus outbreak.

Frontend United, April 30 - May 2 — Minsk, Belarus — This event has been cancelled due to the Coronavirus outbreak.

You Gotta Love Frontend Conference, May 14-15 August 27-28 — Vilnius, Lithuania — Described as having "big names with irresistible talks and a whole lot of fun". This event has been postponed, and will now take place in late August.

🔧 Code, Tools and Resources

Pure CSS Landscape — 'An Evening in Southwold' — This is quite the achievement in realistic CSS art — and you can tweak it. Open up the editor view and alter the color of the sun for your very own personalised sunset.

Ben Evans

Imagine Enjoying PM Software — Clubhouse is fast, delightful, intuitive, and other good adjectives. We're biased, but we think you should try it.

Clubhouse.io sponsor

A List of Web Performance Testing Tools — If you need to identify performance issues with your site this list of tools is a good place to start.

Shawn Wang

Iconset: A Fast SVG Icon Organizer — This is a smart looking native Mac/Windows app to collect, customize, and manage all your icons.

Iconset Creative

broider: Draw Your Own Repeating Border — A browser-based tool for making “9-patch” border patterns. Chris Coyier has done an accompanying write up on this.

Max Bittker

Web Font of the Week

IBM Plex

This typeface from IBM presents a neutral and friendly style across the entire family (made up of a Sans, Sans Condensed, Mono, and Serif variants). The Mono is well suited to displaying code snippets.


by via Frontend Focus

What Are the Best Times to Post Content on Social Media for Optimal Engagement?

Most of the time when you are posting on social media you would want to get maximum engagement on whatever it is that you are actually posting at this current point in time. The fact of the matter is that there are a lot of different ways (including paid and organic) in which you can ensure that no...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Zia Muhammad via Digital Information World

How to Use LinkedIn Ads to Reach Your Target Audience

Are you reaching the right audience on LinkedIn? Wondering how to better target prospects and leads with LinkedIn ads? In this article, you’ll discover how to target your ideal audience with LinkedIn advertising. #1: Use LinkedIn Audience Attributes to Describe Your Ideal Customer We know that LinkedIn is the number-one social media platform for B2B […]

The post How to Use LinkedIn Ads to Reach Your Target Audience appeared first on Social Media Marketing | Social Media Examiner.


by Luan Wise via Social Media Marketing | Social Media Examiner

Facebook's New Program Will Let Users Link Their Brand Loyalty Accounts To Facebook App

In an attempt to compete with the eCommerce giant Amazon, Facebook is planning to introduce a new program which will now let you see your points or rewards which you may have collected by shopping from a brand, all within your favorite Facebook app. The idea of shopping directly from Facebook...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Daniyal Malik via Digital Information World

The Carbonation

The Carbonation
Carbonation is an independent brand of fizzy cocktail mixer. We have developed it’s full brand identity based on basic bubble shape that forms a whimsical secret alphabet.
by via Awwwards - Sites of the day