1578284823
React Hooks were introduced at React Conf October 2018 as a way to use state and side-effects in React function components. Whereas function components have been called functional stateless components (FSC) before, they are finally able to use state with React Hooks. Therefore, many people refer to them as function components now.
In short Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
In this article, we look into the React State Hook.
This is the most commonly used of all the built-in hooks. This is similar to this.setState
, we use it to set the state of our app.
Initially, with ES6 class, we set state like this using setState:
class LoginComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
username: '',
password: ''
}
}
login() {
axios.post('/api/login/', this.state).then((v) => {
// ...
}, (err) => {
// ...
})
}
render() {
return (
<div>
<form>
<input id='username' onInput={()=>this.setState({username: this.value})} />
<input id='password' onInput={()=>this.setState({password: this.value})} />
<button onClick={()=>this.login()}>Login</button>
</form>
</div>
);
}
}
This how we define components our React apps. The props hold the inputs to the component: <LoginComponent show='true' dismiss='false' />
. this.state holds the state of the component. In the this.state, it has username property, which holds the username of the user and the password property which holds the password of the user. When the user enters somethign into the inputs tag, the setState()
function call is used to update the statethis.state with the current username and password.
Using hooks, the above could be done like this:
// login.component.js
import { useState } from 'react'
function handleLogin(login) {
axios.post('/api/login/', login).then((v) => {
// ...
}, (err) => {
// ...
})
}
function LoginComponent() {
const [loginDetails, setLoginDetails] = useState({username: '', password: ''})
return (
<div>
<form>
<input id='username' onInput={()=>setLoginDetails({username: this.value})} />
<input id='password' onInput={()=>setLoginDetails({password: this.value})} />
<button onClick={()=>handleLogin(loginDetails)}>Login</button>
</form>
</div>
);
}
This is the equivalent of our ES6 LoginComponent class. This kind of component defined in a function is known as a stateless component, but with the arrival of Hooks, it is now possible for this stateless component to have their own states. With that, they are now called functional components
.
This LoginComponent
is a functional component. When we input a value in the input boxes it sets the values in the loginDetails.
The new thing here is the useState function. Let’s talk about it:
The useState is the Hook(the state hook) like we said earlier state hooks allow us to manipulate the state of our component. The useState accepts the initial state of the component as a parameter. Like in our app useState({username: '', password: ''})
, the initial state is
{ username: '', password: '' }
We set our initial username and password to be empty strings, so when the user enter his username/password we store it in their respective fields above. If we had done this useState({username: 'nnamdi', password: '123456'}
), then the current state will be:
{username: 'nano', password: '123456'}
We can now have a general function of the useState hook with resp. to the parameters like this:
useState(initialState)
So, pass your initial state to useState function is synonymous to doing this:
// ...
class LoginComponent extends React.Component {
constructor() {
this.state = {
username: "",
password: ""
}
}
// ...
}
in ES6 component classes.
Note: The difference here is that states in this.state are stored in objects but not so in using useState. For example, if you have a component with a single integer age as a state. Using ES6 component classes, it will be represented like this:
class IntComponent extends React.Component {
construcor() {
this.state = {
age: 0
}
}
}
Accessed and manipulated like this:
class IntComponent extends React.Component {
// ...
render() {
return (
<div>
My age is: {this.state.age}
<button onClick={()=>this.setState(age: this.state.age + 1)}>
Increment Age
</button>
</div>
);
}
}
But using the state hook, you simply pass the state age value directly:
function IntComponent () {
const [age,setAge] = useState(0)
// ...
}
The state here doesn’t have to be an object — although it can be if you want.
The useState returns a pair: the current state and the function that lets us update the current state.
const [loginDetails, setLoginDetails] = useState({username: '', password: ''})
Here, the loginDetails
is the current state and setLoginDetails
is the function that will update the state loginDetails
. Since we passed {username: '', password: ''}
to useState, loginDetails
will be {username: '', password: ''}
for the initial render. Actually, useState returns an array, the first in the array is the initial state and the last is the update function, here we destructured loginDetails
and setLoginDetails
from the returned array.
const stateAndUpdateFn = useState({username: '', password: ''})
const loginDetails = stateAndUpdateFn[0]
const setLoginDetails = stateAndUpdateFn[1]
// OR
const [loginDetails, setLoginDetails] = useState({username: '', password: ''})
Updating our general useState function:
const [initialState, setState] = useState(initialState)
`initialState` is the initial state of the component
`setState` is the function that updates the initialState
Looking at our two examples,
LoginComponent
function LoginComponent() {
const [loginDetails, setLoginDetails] = useState({username: '', password: ''})
return (
<div>
<form>
<input id='username' onInput={()=>setLoginDetails({username: this.value})} />
<input id='password' onInput={()=>setLoginDetails({password: this.value})} />
<button onClick={()=>handleLogin(loginDetails)}>Login</button>
</form>
</div>
);
}
We used the setLoginDetails (the second returned value form the useState(…) call) to update the state {username:’’,password:’’}.
Whenever the user enters something in the input boxes, the inputChange event calls the setLoginDetails, this updates loginDetails. If the user entered:
for username => `Vnano`
for password => `957025`
loginDetails will be {username: ‘Vnano’, password: ‘957025’}
In the IntComponent example,
function IntComponent () {
const [age,setAge] = useState(0)
render() {
return (
<div>
My age is: {age}
<button onClick={()=>setAge(age + 1)}>
Increment Age
</button>
</div>
);
}
When the button is clicked the setAge increments the age by one.
Notice in the examples how we don’t append this. (like we always do in ES6 classes) both to the state and to the update function. That’s one cool reason to use Hooks :).
Of course, you must call the update function with the same type as your state.
We can have multiple state variables in our function components.
To demonstrate, we can modify our LoginComponent to manage the username and password states differently:
function LoginCoponent() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
// ...
}
See, we called the useState twice in the same component. We can now independently manage each state.
function LoginCoponent() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
// ...
return (
<div>
<form>
<input id='username' onInput={()=>setUsername(event.target.value)} />
<input id='password' onInput={()=>setPassword(event.target.value)} />
<button onClick={()=>handleLogin(username, password)}>Login</button>
</form>
</div>
);
}
We have only been passing state values to our update function. We can also update our state by passing a function to the update function.
Using our LoginComponent, let’s say we want
function LoginCoponent() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
// ...
return (
<div>
<form>
<input id='username' onInput={()=>setUsername(event.target.value)} />
<input id='password' onInput={()=>setPassword(event.target.value)} />
<button onClick={()=>handleLogin(username, password)}>Login</button>
<button onClick={()=>setUsername(prevUsername => prevUsername + '-vboy')}>Set Username to vboy</button>
</form>
</div>
);
}
This is quite fancy, but it explains it.
We added a button to append -vboy
to the username. See, the setUsername takes a function prevUsername => prevUsername + '-vboy'
. The prevUsername maps to the previous value of username. The function accepts it as an argument and appends s -dinho to it.
If our previous username is vnano
, clicking on the button will call the function with vnano
, the returned string vnano-vboy
will be the current state.
Better example will be to increment and decrement:
function IntComponent () {
const [age,setAge] = useState(0)
render() {
return (
<div>
My age is: {age}
<button onClick={()=>setAge(prevAge=> prevAge+ 1)}>
Increment Age
</button>
<button onClick={()=>setAge(prevAge=> prevAge - 1)}>
Decrement Age
</button>
</div>
);
}
Expensive initialization can cost us severely and it may lead to a bad user experience. To overcome this is to use lazy initialization. What is lazy initialization?
This is a tactic of delaying the creation of value to an identifier or object until the first time it’s needed. If the process is expensive we don’t dont initialized it immediately to avoid lag on the user’s experience. Then, when it is needed by the user it is created.
Hooks offers us the tactic of lazy initialization. If the initial state is an expensive computation. Instead of calculating the state directly and passing it to the useState:
// longOperation takes 30ms to complete
const [initialState, setState] = useState(longOperation())
We can pass a function instead, which will execute on the initial render:
// longOperation takes 30ms to complete
const [initialState, setState] = useState(()=>longOperation())
On subsequent re-renders, the longOperation is not called.
React Hooks doesn’t merge the previous state with the current state of a component. They only return the current state and discard the previous state.
Now, how do we make use of the old state if we want to or how do we merge the two states? Remember, when we pass a function to useState it accepts an argument which is the previous state of our component. With this we can merge the states like this:
const [initialstate, setState] = useState((prevState) => {
return {...prevState, initialState}
})
On this page we’ve learned about one of the Hooks provided by React, called useState. We’re also sometimes going to refer to it as the “State Hook”. It lets us add local state to React function components — which we did for the first time ever!
We also learned a little bit more about what Hooks are. Hooks are functions that let you “hook into” React features from function components. Their names always start with use, and there are more Hooks we haven’t seen yet.
#react #reacthook #javascript
1599097440
A famous general is thought to have said, “A good sketch is better than a long speech.” That advice may have come from the battlefield, but it’s applicable in lots of other areas — including data science. “Sketching” out our data by visualizing it using ggplot2 in R is more impactful than simply describing the trends we find.
This is why we visualize data. We visualize data because it’s easier to learn from something that we can see rather than read. And thankfully for data analysts and data scientists who use R, there’s a tidyverse package called ggplot2 that makes data visualization a snap!
In this blog post, we’ll learn how to take some data and produce a visualization using R. To work through it, it’s best if you already have an understanding of R programming syntax, but you don’t need to be an expert or have any prior experience working with ggplot2
#data science tutorials #beginner #ggplot2 #r #r tutorial #r tutorials #rstats #tutorial #tutorials
1597487833
Here, i will show you how to create dynamic depedent country state city dropdown list using ajax in laravel.
Follow Below given steps to create dynamic dependent country state city dropdown list with jQuery ajax in laravel:
https://www.tutsmake.com/ajax-country-state-city-dropdown-in-laravel/
#how to create dynamic dropdown list using laravel dynamic select box in laravel #laravel-country state city package #laravel country state city drop down #dynamic dropdown country city state list in laravel using ajax #country state city dropdown list using ajax in php laravel #country state city dropdown list using ajax in laravel demo
1596728880
In this tutorial we’ll learn how to begin programming with R using RStudio. We’ll install R, and RStudio RStudio, an extremely popular development environment for R. We’ll learn the key RStudio features in order to start programming in R on our own.
If you already know how to use RStudio and want to learn some tips, tricks, and shortcuts, check out this Dataquest blog post.
[tidyverse](https://www.dataquest.io/blog/tutorial-getting-started-with-r-and-rstudio/#tve-jump-173bb26184b)
Packages[tidyverse](https://www.dataquest.io/blog/tutorial-getting-started-with-r-and-rstudio/#tve-jump-173bb264c2b)
Packages into Memory#data science tutorials #beginner #r tutorial #r tutorials #rstats #tutorial #tutorials
1596513720
What exactly is clean data? Clean data is accurate, complete, and in a format that is ready to analyze. Characteristics of clean data include data that are:
Common symptoms of messy data include data that contain:
In this blog post, we will work with five property-sales datasets that are publicly available on the New York City Department of Finance Rolling Sales Data website. We encourage you to download the datasets and follow along! Each file contains one year of real estate sales data for one of New York City’s five boroughs. We will work with the following Microsoft Excel files:
As we work through this blog post, imagine that you are helping a friend launch their home-inspection business in New York City. You offer to help them by analyzing the data to better understand the real-estate market. But you realize that before you can analyze the data in R, you will need to diagnose and clean it first. And before you can diagnose the data, you will need to load it into R!
Benefits of using tidyverse tools are often evident in the data-loading process. In many cases, the tidyverse package readxl
will clean some data for you as Microsoft Excel data is loaded into R. If you are working with CSV data, the tidyverse readr
package function read_csv()
is the function to use (we’ll cover that later).
Let’s look at an example. Here’s how the Excel file for the Brooklyn borough looks:
The Brooklyn Excel file
Now let’s load the Brooklyn dataset into R from an Excel file. We’ll use the readxl
package. We specify the function argument skip = 4
because the row that we want to use as the header (i.e. column names) is actually row 5. We can ignore the first four rows entirely and load the data into R beginning at row 5. Here’s the code:
library(readxl) # Load Excel files
brooklyn <- read_excel("rollingsales_brooklyn.xls", skip = 4)
Note we saved this dataset with the variable name brooklyn
for future use.
The tidyverse offers a user-friendly way to view this data with the glimpse()
function that is part of the tibble
package. To use this package, we will need to load it for use in our current session. But rather than loading this package alone, we can load many of the tidyverse packages at one time. If you do not have the tidyverse collection of packages, install it on your machine using the following command in your R or R Studio session:
install.packages("tidyverse")
Once the package is installed, load it to memory:
library(tidyverse)
Now that tidyverse
is loaded into memory, take a “glimpse” of the Brooklyn dataset:
glimpse(brooklyn)
## Observations: 20,185
## Variables: 21
## $ BOROUGH <chr> "3", "3", "3", "3", "3", "3", "…
## $ NEIGHBORHOOD <chr> "BATH BEACH", "BATH BEACH", "BA…
## $ `BUILDING CLASS CATEGORY` <chr> "01 ONE FAMILY DWELLINGS", "01 …
## $ `TAX CLASS AT PRESENT` <chr> "1", "1", "1", "1", "1", "1", "…
## $ BLOCK <dbl> 6359, 6360, 6364, 6367, 6371, 6…
## $ LOT <dbl> 70, 48, 74, 24, 19, 32, 65, 20,…
## $ `EASE-MENT` <lgl> NA, NA, NA, NA, NA, NA, NA, NA,…
## $ `BUILDING CLASS AT PRESENT` <chr> "S1", "A5", "A5", "A9", "A9", "…
## $ ADDRESS <chr> "8684 15TH AVENUE", "14 BAY 10T…
## $ `APARTMENT NUMBER` <chr> NA, NA, NA, NA, NA, NA, NA, NA,…
## $ `ZIP CODE` <dbl> 11228, 11228, 11214, 11214, 112…
## $ `RESIDENTIAL UNITS` <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ `COMMERCIAL UNITS` <dbl> 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ `TOTAL UNITS` <dbl> 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ `LAND SQUARE FEET` <dbl> 1933, 2513, 2492, 1571, 2320, 3…
## $ `GROSS SQUARE FEET` <dbl> 4080, 1428, 972, 1456, 1566, 22…
## $ `YEAR BUILT` <dbl> 1930, 1930, 1950, 1935, 1930, 1…
## $ `TAX CLASS AT TIME OF SALE` <chr> "1", "1", "1", "1", "1", "1", "…
## $ `BUILDING CLASS AT TIME OF SALE` <chr> "S1", "A5", "A5", "A9", "A9", "…
## $ `SALE PRICE` <dbl> 1300000, 849000, 0, 830000, 0, …
## $ `SALE DATE` <dttm> 2020-04-28, 2020-03-18, 2019-0…
The glimpse()
function provides a user-friendly way to view the column names and data types for all columns, or variables, in the data frame. With this function, we are also able to view the first few observations in the data frame. This data frame has 20,185 observations, or property sales records. And there are 21 variables, or columns.
#data science tutorials #beginner #r #r tutorial #r tutorials #rstats #tidyverse #tutorial #tutorials
1597487472
Here, i will show you how to populate country state city in dropdown list in php mysql using ajax.
You can use the below given steps to retrieve and display country, state and city in dropdown list in PHP MySQL database using jQuery ajax onchange:
https://www.tutsmake.com/country-state-city-database-in-mysql-php-ajax/
#country state city drop down list in php mysql #country state city database in mysql php #country state city drop down list using ajax in php #country state city drop down list using ajax in php demo #country state city drop down list using ajax php example #country state city drop down list in php mysql ajax