Unit-3 Forms and Hooks in React - JS
Unit-3 Forms and Hooks in React - JS
JS
React Forms
Just like in HTML, React uses forms to allow users to interact with the web page. Forms are an
integral part of any modern web application. It allows the users to interact with the application
as well as gather information from the users. Forms can perform many tasks that depend on
the nature of your business requirements and logic such as authentication of the user, adding
user, searching, filtering, booking, ordering, etc. A form can contain text fields, buttons,
checkbox, radio button, etc.
Components can be of two types:
• Controlled components: In React, Controlled Components are those in which form’s data is
handled by the component’s state.
It takes its current value through props and makes changes through callbacks like onClick,
onChange, etc.
A parent component manages its own state and passes the new values as props to the
controlled component.
In the form elements are either the typed ones like textarea. Input or the selected one like radio
buttons or checkboxes, whenever there is any change, made it is updated accordingly through
some functions that update the state as well.
• Uncontrolled components: The uncontrolled input is similar to the traditional HTML form
inputs.
The DOM itself handles the form data.
Example:
Add a form that allows users to enter their name:
import React from 'react';
export default function App() {
return (
<div>
<form>
This will work as normal, the form will submit and the page will refresh.
We want to prevent this default behavior and let React control the form.
Handling Forms
Handling forms is about how you handle the data when it changes value or gets submitted.
When the data is handled by the components, all the data is stored in the component state.
You can control changes by adding event handlers in the onChange attribute.
We can use the useState Hook to keep track of each inputs value and provide a "single source of
truth" for the entire application.
Submitting Forms
You can control the submit action by adding an event handler in the onSubmit attribute for
the <form>:
Example:
MS. ESHA PATEL Page 4
Unit-3: Forms and Hooks in React.JS
Add a submit button and an event handler in the onSubmit attribute:
import React from 'react';
import { useState } from "react";
export default function App() {
const [name, setName] = useState("");
const handleSubmit = (event) => {event.preventDefault();
alert(`The name you entered was:${name}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" />
</form>
);
}
Output:
To access the fields in the event handler use the event.target.name and event.target.value syntax.
To update the state, use square brackets [bracket notation] around the property name.
Example:
Write a form with two input fields:
import React from 'react';
import { useState } from 'react';
export default function App() {
const [inputs, setInputs] = useState({});
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
name="username"
value={inputs.username || ""}
onChange={handleChange}
/>
</label>
<label>Enter your age:
<input
type="number"
name="age"
value={inputs.age || ""}
onChange={handleChange}
/>
</label>
<input type="submit" />
</form>
)
}
Textarea
The textarea element in React is slightly different from ordinary HTML.
In HTML the value of a textarea was the text between the start tag <textarea> and the end
tag </textarea>.
<textarea>
</textarea>
In React the value of a textarea is placed in a value attribute. We'll use the useState Hook to mange
the value of the textarea:
Example:
A simple textarea with some content:
const [textarea, setTextarea] = useState("The content of a textarea goes in the value attribute");
{ setTextarea(event.target.value) }
return (
<form>
</form>
Output:
in HTML, the selected value in the drop down list was defined with the selected attribute:
HTML:
<select>
In React, the selected value is defined with a value attribute on the select tag:
Example:
A simple select box, where the selected value "Volvo" is initialized in the constructor:
{ setMyCar(event.target.value) }
return (
<form>
<option value="Ford">Ford</option>
<option value="Volvo">Volvo</option>
<option value="Fiat">Fiat</option>
</select>
</form>
React Memo
Using memo will cause React to skip rendering a component if its props have not changed.
React memo is a Higher Order Component (HOC) introduced in React v16.6. As the name suggests,
Memo API uses the memoization technique to optimize performance and makes the application
faster.
The Memo API avoids unnecessary re-renders in functional components and thereby optimizing the
performance of the application.
The Memo API is a HOC that takes in another functional component as a prop, and it will re-render
the component only if there is any change in the props.
Example:
import React,{useState} from "react";
import Todos from "./Todos";
const App = () => {
const [count, setCount] = useState(0);
const [todos, setTodos] = useState(["todo 1", "todo 2"]);
const increment = () => {
setCount((c) => c + 1);
};
React Hooks
Hooks were added to React in version 16.8.
Hooks allow function components to have access to state and other React features. Because of this,
class components are generally no longer needed.
Although Hooks generally replace class components, there are no plans to remove classes from React.
Advantages of Hooks
For React developers, Hooks convey ample benefits as follows:
Example:
Here is an example of a Hook. Don't worry if it doesn't make sense.
import React, { useState } from "react";
export default function App() {
const [color, setColor] = useState("red");
return (
<div>
<h1>My favorite color is {color}!</h1>
<button type="button" onClick={() => setColor("blue")}>Blue</button>
<button type="button" onClick={() => setColor("red")}>Red</button>
<button type="button" onClick={() => setColor("pink")}>Pink</button>
<button type="button" onClick={() => setColor("green")}>Green</button>
</div>
);
}
Output:
Here we are using the useState Hook to keep track of the application state.
Hook Rules
There are 3 rules for hooks:
Import useState
To use the useState Hook, we first need to import it into our component.
Example:
At the top of your component, import the useState Hook.
Initialize useState
We initialize our state by calling useState in our function component.
Example:
Initialize state at the top of the function component.
import { useState } from "react";
function FavoriteColor() {
const [color, setColor] = useState("");
}
Example:
import React, { useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
)
}
Output:
In react useState can be used to read, update, state hold, updating objects and arrays in state.
Some examples of side effects are: fetching data, directly updating the DOM, and timers.
useEffect(<function>, <dependency>)
Example:
import React from 'react';
import { useState , useEffect} from "react";
export default function App() {
const [count, setCount] = useState(0);
useEffect(() =>{
setTimeout(()=>{
setCount((count)=> count+1);
},1000);
});
return <h1>I Have renderes {count} times </h1>;
}
It can be used together with the useState Hook to share state between deeply nested components
more easily than with useState alone.
Create Context
Context Provider
Wrap child components in the Context Provider and supply the state value.
function Component1() {
const [user, setUser] = useState("Jesse Hall");
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 user={user} />
</UserContext.Provider>
);
}
Now, all components in this tree will have access to the user Context.
In order to use the Context in a child component, we need to access it using the useContext Hook.
function Component5() {
const user = useContext(UserContext);
return (
<>
<h1>Component 5</h1>
<h2>{`Hello ${user} again!`}</h2>
</>
);
}
Full Example:
import { useState, createContext, useContext } from "react";
const UserContext = createContext();
export default function Component1() {
const [user, setUser] = useState("Jesse Hall");
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 />
</UserContext.Provider>
);
}
function Component2() {
return (
<>
It can be used to store a mutable value that does not cause a re-render when updated.
The useRef Hook can also be used to keep track of previous state values.
Example:
import { useState, useEffect, useRef } from "react";
export default function App() {
const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");
useEffect(() => {
previousInputValue.current = inputValue;
}, [inputValue]);
return (
<div>
<input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)}/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value: {previousInputValue.current}</h2>
</div>
);
}
Output:
If you find yourself keeping track of multiple pieces of state that rely on complex
logic, useReducer may be useful.
Syntax
The useReducer Hook accepts two arguments.
useReducer(<reducer>, <initialState>)
The reducer function contains your custom state logic and the initialStatecan be a simple value but
generally will contain an object.
Example:
import { useReducer } from "react";
const initialTodos = [
{
id: 1,
This allows us to isolate resource intensive functions so that they will not automatically run on every
render.
The useCallback Hook only runs when one of its dependencies update.
The useCallback and useMemo Hooks are similar. The main difference is that useMemo returns
amemoized value and useCallback returns a memoized function.
Example:
App.js:
import { useState, useCallback } from "react";
import Todos from "./Todos";
const App = () => {
const [count, setCount] = useState(0);
const [todos, setTodos] = useState([]);
return (
<>
<Todos todos={todos} addTodo={addTodo} />
<hr />
<div>
The useMemo Hook only runs when one of its dependencies update.
The useMemo Hook can be used to keep expensive, resource intensive functions from needlessly
running.
When changing the count or adding a todo, you will notice a delay in execution.
To fix this performance issue, we can use the useMemo Hook to memoize
the expensiveCalculation function. This will cause the function to only run when needed.
The useMemoHook accepts a second parameter to declare dependencies. The expensive function will
only run when its dependencies have changed.
Example:
import { useState, useMemo } from "react";
When you have component logic that needs to be used by multiple components, we can extract that
logic to a custom Hook.
Build a Hook
In the following code, we are fetching data in our Home component and displaying it.
We will use the JSONPlaceholder service to fetch fake data. This service is great for testing
applications when there is no existing data.
Use the JSONPlaceholder service to fetch fake "todo" items and display the titles on the page:
Example:
App.js:
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos")
}, []);
return (
<div>
{data &&
data.map((item) => {
</div>
);
};
The fetch logic may be needed in other components as well, so we will extract that into a custom
Hook.
Example:
useFetch.js:
useEffect(() => {
fetch(url)
}, [url]);
return [data];
};
App.js:
return (
<div>
{data &&
data.map((item) => {
})}
</div>
);
};
Advantages
It provides reusability of the code.