1672947540
In this article, we will learn about the Difference Between Vue Composition API Vs React Hook. React Hooks were introduced with the React 16.8 update, and since then, they have become a necessity for single-page applications. They are a function type that allows you to hook into React state and lifecycle methods.
With the introduction of the Vue 3 update, Vue.js has challenged React with its new Composition API, which can extract pieces of reactive logic and share the code with other components.
This article will compare the Vue Composition API and React Hooks to help you understand the differences and similarities between them.
React Hooks are only featured in React functional components. These functional components execute with every rerender.
The following code example demonstrates how to use React Hooks. Initially, import the useState and useEffect Hooks from React. Next, use the useState Hook to add a local state inside the React functional component. Finally, use the changing function of useState to increment the value of the count with the help of the button onClick event. This useEffect runs on every render and will update the document title with its current value.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = You clicked ${count} times ;
});
return (
<div><p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
/**
* when you click 10 times,
* document title and paragraph will be displayed as "You clicked 10 times."
*/
}
export default Example;
In Vue 3, a component is an object, and it can be defined with the setup() method introduced with the Composition API. You may feel that the React functional component’s body and Vue’s setup() operation work similarly. But the setup() method is only executed once, and it acts as an entry point to the Composition API. With the help of that, we can define a state, and this avoids recreating the state with every call.
The following code example shows only the script part of the Vue component. On top of it, we imported watchEffect and ref to define a variable and keep track of it. Inside the setup component, the price is defined with an initial value. The console log will give the updated value every time the price changes.
<script>
import { watchEffect, ref, defineComponent } from "vue";
export default defineComponent({
name: "Store",
setup() {
const price = ref(10);
watchEffect(() => console.log(price.value));
return {
price
};
},
});
</script>
<template>
<h3>Price</h3>
<input v-model="price" id="price" placeholder="edit me">
</template>
useState is famous among the React Hooks and helps us to claim reactive objects. A two-member array represents the React useState, the first being the current value and the second being the function that can change the value.
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
You can define the reactive object inside the new setup() component in the Vue Composition API. Unlike in React, you do not need to provide a mutation function (setCount) to change the value.
<template>
<p>You clicked {{count}} times</p>
<button @click="count += 1">
Click me
</button>
</template>
<script>
import { ref } from "vue";
export default {
name: "Hooks",
setup() {
let count = ref(0);
return {
count,
};
},
};
</script>
React has defined some rules for utilizing Hooks:
Although these rules prevent issues like changing the order of Hooks execution by calling Hooks inside conditional blocks, the default behavior of setup() in Vue will prevent them, as it executes before the component is created.
Vue draws more lines to perform the same functionality possible with a single line of React code. So yes, React Hooks is a valid choice for an elementary code like this. But when the code is complex, it will be easier to use the Vue Composition API than React Hooks. So, let’s add more variables and examine what looks better.
// React
const [name, setName = useState('Apple');
const [price, setPrice] = useState(20);
const [quantity, setQuantity] = useState(100);
// Vue
setup () {
return {
name: ref('Apple'),
price: ref(20),
quantity: ref(100)
}
}
So, it’s a win for Vue’s Composition API.
Let’s now see how to update the value of a variable. This comparison might be your decisive point in the battle between React Hooks and the Vue Composition API.
Inside the React function component, we defined a local state called name with its initial value, Apple. Then, we introduced an input element with an onChange event to change the value.
import { useState } from 'react';
function Example() {
const [name, setName] = useState('Apple');
return (
<form>
<input
type="text"
value=name
onChange={e => setName(e.target.value)}
/>
<h2>My favorite fruit is {name}</h2>
</form>
)
}
Even though React tries to use native JavaScript whenever possible, Vue has new syntaxes like v-model making the code look pretty. The following example shows how we change the value of the local state name by using an input field.
<script>
import {ref} from 'vue'export default {
setup(){
return {
name: ref('Apple')
}
}
}
</script>
<template>
<form>
<input type="text" v-model="name"/>
<h2>My favorite fruit is {{name}} </h2>
</form>
</template>
The previous code example demonstrates how easily you can change a variable with Vue. The main point is that the Vue code is more precise and readable. Such well-organized code will be handy when debugging.
Examples of side effects include data fetching, setting up a subscription, and manual modification of the DOM. React attempts to handle side effects using the useEffect Hook.
The following useEffect Hook does not use any dependencies. With every render of the function, useEffect will be executed. It continuously updates the document title with the current value of the count state.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button></div>
);
}
The Composition API has two methods for dealing with side effects, watch and watchEffect. Nevertheless, they have their uses.
When multiple variables change, React’s useEffect allows the developer to keep track of these variables and activate a callback function. watchEffect is something we especially think of with Vue’s Composition API, but it does not keep track of the variable values. To achieve that, we have to use a watch().
The following example shows how to implement watchEffect. Whenever the price value changes, watchEffect will be executed and give the console log.
<script>
import { watchEffect, ref, defineComponent } from "vue";
export default defineComponent({
setup() {
const price = ref(100);
watchEffect(() =>
console.log(price.value))
);
return {
price
};
},
});
</script>
Case 01:
useEffect(() => {
//Runs on every render.
});
Case 02:
useEffect(() => {
//Runs only on the first render.
}, []);
Case 03:
useEffect(() => {
//Runs with first render OR whenever the dependency value changes.
}, [prop, state]);
watch ()— This works very similar to useEffect. We have to tell it when to run the callback function.
//The callback is called whenever `refA` changes.
watch(refA, () => {
console.log(refA.value);
});
watchEffect — With this, we don’t need to add specific dependencies manually. It will run the callback function whenever the reactive variables we use inside it change. And watchEffect works outside of a Vue component.
//The callback is called immediately, and
//whenever `refA` or `refB` changes ...
watchEffect(() => {
console.log(refA.value);
console.log(refB.value);
});
The basis for everything we discussed throughout this article is JavaScript. So first, we went through the React Hooks and alternatives provided by Vue Composition API.
React does not attempt to deviate much of its code from Vanilla JavaScript. And Vue uses fewer lines of code and less time to perform the same operation that React Hooks does. We realized that the Vue code is more precise and readable, which means it has a higher maintenance capability. If you intend to switch from one to the other or are in the stage of choosing between React and Vue, I hope this article gives you a few insights. Thank you for reading!
Original article sourced at: https://www.syncfusion.com
1598839687
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.
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:
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:
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
1607768450
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
1595396220
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.
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:
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
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.
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.
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.
APIs are used in a way that increases the probability credentials are leaked:
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.
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)
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.
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.
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.
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
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
1601381326
We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.
The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:
With regards to how the APIs are shared:
#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway
1602643749
In this article, we will take a look at **_useEffect _**React hook to fetch data from an API. We will create a sample React application to pull data from the provider and use it in our application.
Let’s create a new React application using the following command:
npx create-react-app react-useeffect-demo
#react #javascript #reactjs #react-hooks #react-hook #api