Zara  Bryant

Zara Bryant

1559881581

How to Replace Redux with React Hooks and the Context API

You’ll learn a new way of handling state in your React projects without writing excessive code or installing a bunch of libraries as is the case with Redux. React hooks allows you to use local state inside of function components, while the Context API allows you to share state with other components.

The most popular way for handling shared application state in React is using a framework such as Redux. Quite recently, the React team introduced several new features which include React Hooks and the Context API. These two features effectively eliminated a lot of challenges that developers of large React projects have been facing. One of the biggest problems was ‘prop drilling’ which was common with nested components. The solution was to use a state management library like Redux. This unfortunately came with the expense of writing boilerplate code — but now, it’s possible to replace Redux with React Hooks and the Context API.

Prerequisites

The technique you will learn here is based on patterns that were introduced in Redux. This means you need to have a firm understanding of reducers and actions before proceeding. I am currently using Visual Studio Code, which seems to be the most popular code editor right now (especially for JavaScript developers). If you are on Windows, I would recommend you install Git Bash. Use the Git Bash terminal to perform all commands provided in this tutorial. [Cmder](https://cmder.net/) is also a good terminal capable of executing most Linux commands on Windows.

You can access the complete project used in this tutorial from this GitHub Repository.

About the New State Management Technique

There are two types of state that we need to deal with in React projects:

  • local state
  • global state

Local states can only be used within the components that were created. Global states can be shared across several components. Either way, they are two ways of declaring and handling state using React hooks:

  • useState
  • useReducer

useState is recommended for handling simple values like numbers or strings. However, when it comes to handling complex data structures, you will need to use useReducer. Unlike useState that only comes with a setValue function, the useReducer hook allows you to specify as many functions as you need. For example, an object array state will need at least functions for adding, updating and deleting an item.

Once you declare your state using either useState or useReducer, you can lift it up to global using React Context. This is the technology that will allow you to share values between components without having to pass down props. When you declare a Context Object, it serves as Provider for other components to consume and subscribe to context changes. You can add as many component consumers as you want to the provider. The shared state will sync up automatically with all subscribed components.

Let’s start creating the project so that you can have practical knowledge of how it all works.

Setting Up the Project

The easiest way to create a project is to use create-react-app tool. However, the tool does install a ton of development dependencies that consume a lot of disk space. As a result, it takes a longer time to install and a longer time to spin up the dev server. If you don’t mind the minor issues, you can go ahead a create a new React project with the tool. You can call it react-hooks-context-demo.

Another way of creating a new React project is by cloning a starter project configured to use Parcel JS as the builder. This method consumes at least 50% less disk space and starts the dev server faster than the create-react-app tool. I’ve created one specifically for React tutorials such as this one. I would recommend that you first create a completely blank GitHub repository on your account, before you proceed with these instructions:

$ git clone git@github.com:brandiqa/react-parcel-starter.git react-hooks-context-demo
$ cd react-hooks-context-demo
$ git remote rm origin
# Replace `username` and `repositoryName` with yours
$ git remote add origin git@github.com:username/repositoryName.git
$ git config master.remote origin
$ git config master.merge refs/heads/master
$ git push -u origin master
# Install dependencies
$ npm install

After you have completed executing all the above instructions, you can use the command npm start to start the dev server. You’ll need to launch your browser and navigate to the page localhost:1234.

How to Replace Redux with React Hooks and the Context API

If you used the create-react-app tool, it will of course look different. That is okay since we’ll change the default view in the next step. If your project has started up fine, you can move on to the next section.

Installing a User Interface Library

This step is not necessary for this topic. However, I always like building clean and beautiful interfaces with the least amount of effort. For this tutorial, we’ll use Semantic UI React. Since this is a tutorial about state management, I won’t explain how the library works. I’ll only show you how to use it.

npm install semantic-ui-react semantic-ui-css 

Open index.js and insert the following imports:

import 'semantic-ui-css/semantic.min.css';
import './index.css';

That’s all we need to do for our project to start using Semantic UI. Let’s start working on the first example demonstrating this new state management technique.

Counter Example

In this example, we’ll build a simple counter demo consisting of two buttons and a display button. In order to demonstrate global state, this example will be made up of two presentational components. First, we’ll need to define our context object where the state will live. It is similar to store in Redux. Creating our context code to be used for this purpose will require a bit of boilerplate code that will need to be duplicated in every project. Luckily, someone has already written a custom hook for this which will allow you to create your context object in a single line. Simply install the [constate](https://www.npmjs.com/package/constate) package:

npm install constate 

With that installed, you should be able to proceed. I’ve placed comments in the code to explain what is happening. Create the store context object file context/CounterContext.js and insert this code:

import { useState } from "react";
import createUseContext from "constate"; // State Context Object Creator

// Step 1: Create a custom hook that contains your state and actions
function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(prevCount => prevCount + 1);
  const decrement = () => setCount(prevCount => prevCount - 1);
  return { count, increment, decrement };
}

// Step 2: Declare your context state object to share the state with other components
export const useCounterContext = createUseContext(useCounter);

Create the parent component views/Counter.jsx and insert this code:

import React from "react";
import { Segment } from "semantic-ui-react";

import CounterDisplay from "../components/CounterDisplay";
import CounterButtons from "../components/CounterButtons";
import { useCounterContext } from "../context/CounterContext";

export default function Counter() {
  return (
    // Step 3: Wrap the components you want to share state with using the context provider
    
      ### Counter

      
        
        
      
    
  );
}

Create the presentation component components/CounterDisplay.jsx and insert this code:

import React from "react";
import { Statistic } from "semantic-ui-react";
import { useCounterContext } from "../context/CounterContext";

export default function CounterDisplay() {
  // Step 4: Consume the context to access the shared state
  const { count } = useCounterContext();
  return (
    
      {count}
      Counter
    
  );
}

Create the presentation component components/CounterButtons.jsx and insert this code:

import React from "react";
import { Button } from "semantic-ui-react";
import { useCounterContext } from "../context/CounterContext";

export default function CounterButtons() {
  // Step 4: Consume the context to access the shared actions
  const { increment, decrement } = useCounterContext();
  return (
    
      
        
          Add
        
        
          Minus
        
      
    
  );
}

Replace the code in App.jsx with this:

import React from "react";
import { Container } from "semantic-ui-react";

import Counter from "./views/Counter";

export default function App() {
  return (
    
      # React Hooks Context Demo

      
    
  );
}

Your browser page should have the following view. Click the buttons to ensure that everything is working:

How to Replace Redux with React Hooks and the Context API.

Hope this example makes sense — read the comments I’ve included. Let’s go to the next section where we’ll set up an example that is a bit more advanced.

Contacts Example

In this example, we’ll build a basic CRUD page for managing contacts. It will be made up of a couple of presentational components and a container. There will also be a context object for managing contacts state. Since our state tree will be a bit more complex than the previous example, we will have to use the useReducer hook.

Create the state context object context/ContactContext.js and insert this code:

import { useReducer } from "react";
import _ from "lodash";
import createUseContext from "constate";

// Define the initial state of our app
const initialState = {
  contacts: [
    {
      id: "098",
      name: "Diana Prince",
      email: "diana@us.army.mil"
    },
    {
      id: "099",
      name: "Bruce Wayne",
      email: "bruce@batmail.com"
    },
    {
      id: "100",
      name: "Clark Kent",
      email: "clark@metropolitan.com"
    }
  ],
  loading: false,
  error: null
};

// Define a pure function reducer
const reducer = (state, action) => {
  switch (action.type) {
    case "ADD_CONTACT":
      return {
        contacts: [...state.contacts, action.payload]
      };
    case "DEL_CONTACT":
      return {
        contacts: state.contacts.filter(contact => contact.id != action.payload)
      };
    case "START":
      return {
        loading: true
      };
    case "COMPLETE":
      return {
        loading: false
      };
    default:
      throw new Error();
  }
};

// Define your custom hook that contains your state, dispatcher and actions
const useContacts = () => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const { contacts, loading } = state;
  const addContact = (name, email) => {
    dispatch({
      type: "ADD_CONTACT",
      payload: { id: _.uniqueId(10), name, email }
    });
  };
  const delContact = id => {
    dispatch({
      type: "DEL_CONTACT",
      payload: id
    });
  };
  return { contacts, loading, addContact, delContact };
};

// Share your custom hook
export const useContactsContext = createUseContext(useContacts);

Create the parent component views/Contacts.jsx and insert this code:

import React from "react";
import { Segment, Header } from "semantic-ui-react";
import ContactForm from "../components/ContactForm";
import ContactTable from "../components/ContactTable";
import { useContactsContext } from "../context/ContactContext";

export default function Contacts() {
  return (
    // Wrap the components that you want to share your custom hook state
    
      
        Contacts
        
        
      
    
  );
}

Create the presentation component components/ContactTable.jsx and insert this code:

import React, { useState } from "react";
import { Segment, Table, Button, Icon } from "semantic-ui-react";
import { useContactsContext } from "../context/ContactContext";

export default function ContactTable() {
  // Subscribe to `contacts` state and access `delContact` action
  const { contacts, delContact } = useContactsContext();
  // Declare a local state to be used internally by this component
  const [selectedId, setSelectedId] = useState();

  const onRemoveUser = () => {
    delContact(selectedId);
    setSelectedId(null); // Clear selection
  };

  const rows = contacts.map(contact => (
    <Table.Row
      key={contact.id}
      onClick={() => setSelectedId(contact.id)}
      active={contact.id === selectedId}
    >
      {contact.id}
      {contact.name}
      {contact.email}
    
  ));

  return (
    
      
        
          
            Id
            Name
            Email
          
        
        {rows}
        
          
            
            
              <Button
                floated="right"
                icon
                labelPosition="left"
                color="red"
                size="small"
                disabled={!selectedId}
                onClick={onRemoveUser}
              >
                 Remove User
              
            
          
        
      
    
  );
}

Create the presentation component components/ContactForm.jsx and insert this code:

import React, { useState } from "react";
import { Segment, Form, Input, Button } from "semantic-ui-react";
import { useContactsContext } from "../context/ContactContext";

export default function ContactForm() {
  const name = useFormInput("");
  const email = useFormInput("");
  // Consume the context store to access the `addContact` action
  const { addContact } = useContactsContext();

  const onSubmit = () => {
    addContact(name.value, email.value);
    // Reset Form
    name.onReset();
    email.onReset();
  };

  return (
    
      
        
          
            
          
          
            
          
          
            
              New Contact
            
          
        
      
    
  );
}

function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  function handleChange(e) {
    setValue(e.target.value);
  }

  function handleReset() {
    setValue("");
  }

  return {
    value,
    onChange: handleChange,
    onReset: handleReset
  };
}

Insert the following code in App.jsx accordingly:

import Contacts from "./views/Contacts";
//...

  # React Hooks Context Demo

  {/*  */}
  
;

After implementing the code, your browser page should refresh. To delete a contact, you need to select a row first then hit the ‘Delete button’. To create a new contact, simply fill the form and hit the ‘New Contact’ button.

How to Replace Redux with React Hooks and the Context API

Go over the code to make sure you understand everything. Read the comments that I’ve included inside the code.

Summary

Hope both these examples provide an excellent understanding of how you can manage shared application state without Redux. If you were to rewrite these examples without hooks and the context API, it would have resulted in a lot more code. You should only use the context API where applicable. Props should have been used in these examples if this wasn’t a tutorial.

You may have noticed in the second example that there are a couple of unused state variables i.e. loading and error. As a challenge, you can progress this app further to make use of them. For example, you can implement a fake delay, and cause the presentation components to display a loading status. You can also take it much further and access a real remote API. This is where the error state variable can come handy in displaying error messages.

The only question you may want to ask yourself now: is Redux necessary for future projects? One disadvantage that I’ve seen with this technique is that you can’t use the Redux DevTool Addon to debug your application state. However, this might change in the future with the development of a new tool. Obviously as a developer, you will still need to learn Redux in order to maintain legacy projects. If you are starting a new project, you will need to ask yourself and your team if using a state management library is really necessary for your case.

#reactjs #redux #javascript

What is GEEK

Buddha Community

How to Replace Redux with React Hooks and the Context API
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

How to Use Redux with React Hooks🔥 ( REDUX HOOKS )

Hello Friends,
In this Video, We are going to know How to use redux with react hook.
we have used redux inside Class based component with Connect() higher order component
but inside the functional based component , We couldnt use Connect!
So How can we use redux in fucntional based component ?
We will figure out it here !

Git Repository:
https://github.com/jaewonhimnae/reduxHooks-with-reactHooks

#redux #redux hooks #react hooks #react

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

DARK MODE App with REACT Hook , REDUX Hook, Styled Components

Thank you for watching this video !
git repository :
https://github.com/jaewonhimnae/react-darkmode-app

#react hook #react #redux #redux hook