20 Essential React Tools for 2020

.gitignore 3D accessibility accessible headings ad banner ad revenue ad revenues adobe XD Advanced advanced-css-tools advanced-css-tutorials AdvancedCSS AdvancedCSS-hub agency Agile Agile Development ai Ajax Alex Skill Kit Alexa Alexa skill AlexW Amazon Alexa amazon developer analytics Angelap angular AngularJS Animation anime.js ANN api apollo Appsflyer ARIA aria attributes array methods artificial neural network Async async components AurelioD automation Avocode AWS AWS Lambda axios b2b b2c baas background background eraser tool Banner banner ad Bannersnack bash bash commands bawmedia bem bitcoin black friday Blogs bootstrap bot browser testing Browsers build process bundler Business business success C Canvas & SVG career Career Advancement CDN Chakra UI charting chat app chatbots ChatKit chrome chrome developer tools chrome extension chrome extensions chromium ciphering cli cli tools climate climate action clip-path clojure cloning Cloud cloud hosting CloudFlare Cloudways cms CNN code challenge ColinI collaboration collaboration tools color contrast committing changes compiler components conflicts const assertions constructs content content delivery network content organization context api convoluted neural network create react app cron job cross browser testing cross platform development cross-browser cryptocurrencies cryptocurrency CSS CSS Animations CSS Architecture css blur css challenge css framework css frameworks css grid css layout css master css modules CSS print css rem css typography CSS-in-JS CSS3 css3 transforms cssbattle.dev D3.js data science data visualization database databases debugging decoupled cms deep linking delay Design Design & UX design career design handoff Detox dev environment developer job developer tools DevOps devtools diagnostic analytics digit recognition digital agency digitalocean Discord discounts django Docker Docker Containers drag & drop dropzone.js E-commerce ECMAScript edge computing editor elastic em units employment encryption end-to-end testing energy energy usage Entrepreneur Entrepreneurship environment erasing backgrounds es6 ES6 classes eslint Expo Express FaaS face detection face recognition fast wordpress themes Feathers Feathers.js figma flask flatfile flexible wordpress theme forking form validation forms tutorial framework Frameworks freelancing functional programming functions gatsby generators geolocation get organized getting a job GIPHY git git branching git lfs git merging gitCS github github API Google Photos GraphCMS graphing graphql Growth Grunt grunt-watch Gulp haskell headless CMS hide and show page elements hooks hosting HTML HTML & CSS html preprocessor HTML5 HTML5 Dev Center HTML5 Tutorials & Articles https://www.sitepoint.com/windows-linux-subsystem-2-windows-terminal IAAS IDE Illustration image optimization immutability Interview ionic IP2Location ipdata jade jamesh JavaScript javascript framework javascript frameworks javascript tooling Jest job job hunting job interview joelf jQuery jQuery functions jquery get url params jquery string functions jQuery.each() jQuery.each() Array Example jquery4u js js framework JS tooling Keras keycdn kubernetes lambdatest launch checklist Layout learn javascript learn typescript learn-advanced-css learn-modernjs Learn-Node-JS learn-vue Let's Encrypt Lift linux linux containers location tracking LouisL machine learning Managed managed hosting managing remotes mariap marvel MATLAB MBaaS mekanism mental health merging mind map mind mapping mindmapping Mobile mobile attribution Mobile Design modern css modernjs modernjs-hub modernjs-tools modernjs-tutorials modules moment.js monday mongodb MTCNN multi-threading mysql MySQL install natural language processing Navigation navigation library nest Next.js nginx nilsonj no-code node node version manager node-hub Node-JS-Tools Node-JS-Tutorials node-mysql module Node.js NodeGui nodejs noops nosql npm nvm objects octobercms Offers on-premise online publishing organize organize files PaaS Package Management package manager pair programming pairing patrickc pause Percy Performance Photography & Imagery Photoshop Photoshop Tutorials & Articles pip pipeline portfolio portfolio builders preprocessors prettier print styles Prisma Private Class Fields product design Productivity productivity tips Profitability Programming programming job PubNub Pug Puppeteer Pusher python python framework python interview python job Quasar query strings quick-tip quiz quote builders r Raw JavaScript React react components React Hooks React Hooks Form React native React-Tools reactive Reactive Programming reactive web apps read offline Reat native elements Recurring Payments recursive types RedBox redux rem units remote job remote work remote work tips remote working removing backgrounds resilient Resources responsive REST restful api Review SaaS sampling sass Scss self sencha server server-side serverless serverless computing shared hosting sharing state sharpen shell shell commands side project siteground sketch slashdata sleep Software software commits sorting sourcetree specifications speech recognition speech recognition api sponsored sql ssl Stack Overflow Startups state state management static module bundler StudioWorks Styled Components styling React components survey sustainability svelte sympli Tailwind task runner telegram bots Template engine Testing text to speech Themes Tic Tac Toe Tinder toggle Tolerance tooling tooling anxiety tools Tools & Libraries transformations TypeScript typescript skills Ubuntu UI UI Design Usability user experience user research UX ux issues vanilla javascript VGGFace2 virtual machine visual testing voice recognition vps vue Vue CLI vue dev environment vue-hub vue-tutorials vue.js vuetify vuex wait WatermelonDB Web Web Design web hosting Web Hosting & Domains Web standards web workers webpack website builders website performance WebSockets windows windows 10 home Windows Subsystem for Linux Windows Terminal wix women women in tech WordPress wordpress plugin wordpress themes WordPress theming work workers workflow working remotely workplaces WPEngine WSL WSL2 YellowBox Zeplin zsh zsh command zsh plugin zsh tools

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.

Original Article

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.