0% found this document useful (0 votes)
242 views33 pages

Unit-3 Forms and Hooks in React - JS

The document discusses forms and hooks in React. It covers adding, handling, and submitting forms as well as controlled and uncontrolled components. It also discusses various form elements like textarea, select dropdown, and handling multiple input fields. The document then provides an overview of hooks in React including common hooks like useState, useEffect, useContext and their advantages.

Uploaded by

Rishi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
242 views33 pages

Unit-3 Forms and Hooks in React - JS

The document discusses forms and hooks in React. It covers adding, handling, and submitting forms as well as controlled and uncontrolled components. It also discusses various form elements like textarea, select dropdown, and handling multiple input fields. The document then provides an overview of hooks in React including common hooks like useState, useEffect, useContext and their advantages.

Uploaded by

Rishi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 33

Unit-3: Forms and Hooks in React.

JS

3.1 Forms: (Adding forms, Handling forms, Submitting forms)


3.1.1 Event.target.name and event. Target.event, React Memo
3.1.2 Components (TextArea, Drop down list (SELECT))
3.2 Hooks: Concepts and Advantages
3.2.1 useState, useEffect, useContext
3.2.2 useRef, useReducer, useCallback, useMemo
3.2.3 Hook: Building custom hook, advantages and use

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.

MS. ESHA PATEL Page 1


Unit-3: Forms and Hooks in React.JS
Here, the HTML elements maintain their own state that will be updated when the input value
changes.
To write an uncontrolled component, you need to use a ref to get form values from the DOM.
In other words, there is no need to write an event handler for every state update. You can use
a ref to access the input field value of the form from the DOM.

Adding Forms in React


You add a form with React like any other element:

Example:
Add a form that allows users to enter their name:
import React from 'react';
export default function App() {
return (
<div>
<form>

MS. ESHA PATEL Page 2


Unit-3: Forms and Hooks in React.JS
<label>Enter your name:
<input type="text" />
</label>
</form>
</div>
)
}
Output:

This will work as normal, the form will submit and the page will refresh.

But this is generally not what we want to happen in React.

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.

In HTML, form data is usually handled by the DOM.

In React, form data is usually handled by the components.

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.

MS. ESHA PATEL Page 3


Unit-3: Forms and Hooks in React.JS
Example:
Use the useState Hook to manage the input:
import { useState } from 'react';
import React from 'react'
export default function App() {
const [name, setName] = useState("");
return (
<div>
<form>
<label>Enter your name:
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
</label>
</form>
</div>
)
}
Output:

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:

MS. ESHA PATEL Page 5


Unit-3: Forms and Hooks in React.JS

Multiple Input Fields


You can control the values of more than one input field by adding a name attribute to each element.

We will initialize our state with an empty object.

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({});

const handleChange = (event) => {


const name = event.target.name;
const value = event.target.value;
setInputs(values => ({...values, [name]: value}))
}

MS. ESHA PATEL Page 6


Unit-3: Forms and Hooks in React.JS
const handleSubmit = (event) => {
event.preventDefault();
alert(inputs);
console.log(inputs);
}

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>
)
}

MS. ESHA PATEL Page 7


Unit-3: Forms and Hooks in React.JS
Output:

Event.target.name and event. Target.event


• To handle the values of more than one input field event handlers
evnt.target.name and event.target.value is used.
• Values of multiple input fields are managed by giving name attribute to each
element.
• Square bracket is used around the property name to update the state. State is
generally initialized with empty object.

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>

Content of the 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:

MS. ESHA PATEL Page 8


Unit-3: Forms and Hooks in React.JS
import { useState } from 'react';

export default function App() {

const [textarea, setTextarea] = useState("The content of a textarea goes in the value attribute");

const handleChange = (event) =>

{ setTextarea(event.target.value) }

return (

<form>

<textarea value={textarea} rows={2} cols={30} onChange={handleChange} />

</form>

Output:

Drop down list (Select)


A drop down list, or a select box, in React is also a bit different from HTML.

in HTML, the selected value in the drop down list was defined with the selected attribute:

HTML:
<select>

MS. ESHA PATEL Page 9


Unit-3: Forms and Hooks in React.JS
<option value="Ford">Ford</option>
<option value="Volvo" selected>Volvo</option>
<option value="Fiat">Fiat</option>
</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:

import React from 'react';

import { useState } from 'react';

export default function App() {

const [myCar, setMyCar] = useState("Volvo");

const handleChange = (event) =>

{ setMyCar(event.target.value) }

return (

<form>

<select value={myCar} onChange={handleChange}>

<option value="Ford">Ford</option>

<option value="Volvo">Volvo</option>

<option value="Fiat">Fiat</option>

</select>

</form>

MS. ESHA PATEL Page 10


Unit-3: Forms and Hooks in React.JS
Output:

React Memo
Using memo will cause React to skip rendering a component if its props have not changed.

This can improve performance.

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);
};

MS. ESHA PATEL Page 11


Unit-3: Forms and Hooks in React.JS
return (
<div>
<Todos todos={todos} />
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
</div>
</div>
);
};
export default App;
Todos.js:
import { memo } from "react";
const Todos = ({ todos }) => {
console.log("child render");
return (
<div>
<h2>My Todos</h2>
{todos.map((todo, index) => {
return <p key={index}>{todo}</p>;
})}
</div>
);
};
export default memo(Todos);
Output:

MS. ESHA PATEL Page 12


Unit-3: Forms and Hooks in React.JS

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:

• You can write concise and clearer code.


• Hooks are simpler to work with and test. Code would appear cleaner and easier to read.
• A related logic could be tightly coupled inside a custom hook.
• It simplifies how to make code more composable and reusable.
• Unlike HOCs, they don’t create another element in DOM.
• Hooks would work more efficiently with the future React optimizations. For example, it would
work ahead of time compilation as well as components folding.
• Components folding may be implemented in the future. It suggests that for code elimination at
compile-time, hooks are simple to reuse the stateful logic.

MS. ESHA PATEL Page 13


Unit-3: Forms and Hooks in React.JS
What is a Hook?
Hooks allow us to "hook" into React features such as state and lifecycle methods.

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:

You must import Hooks from react.

Here we are using the useState Hook to keep track of the application state.

MS. ESHA PATEL Page 14


Unit-3: Forms and Hooks in React.JS
State generally refers to application data or properties that need to be tracked.

Hook Rules
There are 3 rules for hooks:

• Hooks can only be called inside React function components.


• Hooks can only be called at the top level of a component.
• Hooks cannot be conditional

Notes: Hooks will not work in React class components.

React useState Hook


The React useState Hook allows us to track state in a function component.

State generally refers to data or properties that need to be tracking in an application.

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.

import { useState } from "react”;'

Notice that we are destructuring useState from react as it is a named export.

Initialize useState
We initialize our state by calling useState in our function component.

useState accepts an initial state and returns two values:

MS. ESHA PATEL Page 15


Unit-3: Forms and Hooks in React.JS
• The current state.
• A function that updates the state.

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:

MS. ESHA PATEL Page 16


Unit-3: Forms and Hooks in React.JS

In react useState can be used to read, update, state hold, updating objects and arrays in state.

React useEffect Hooks


The useEffect Hook allows you to perform side effects in your components.

Some examples of side effects are: fetching data, directly updating the DOM, and timers.

useEffect accepts two arguments. The second argument is optional.

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>;
}

MS. ESHA PATEL Page 17


Unit-3: Forms and Hooks in React.JS

React useContext Hook


React Context is a way to manage state globally.

It can be used together with the useState Hook to share state between deeply nested components
more easily than with useState alone.

Create Context

To create context, you must Import createContext and initialize it:

import { useState, createContext } from "react";


import ReactDOM from "react-dom/client";
const UserContext = createContext()

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.

Use the useContext Hook

In order to use the Context in a child component, we need to access it using the useContext Hook.

MS. ESHA PATEL Page 18


Unit-3: Forms and Hooks in React.JS
First, include the useContext in the import statement:

import { useState, createContext, useContext } from "react";

Then you can access the user Context in all components:

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 (
<>

MS. ESHA PATEL Page 19


Unit-3: Forms and Hooks in React.JS
<h1>Component 2</h1>
<Component3 />
</>
);
}
function Component3() {
return (
<>
<h1>Component 3</h1>
<Component4 />
</>
);
}
function Component4() {
return (
<>
<h1>Component 4</h1>
<Component5 />
</>
);
}
function Component5() {
const user = useContext(UserContext);
return (
<>
<h1>Component 5</h1>
<h2>{`Hello ${user} again!`}</h2>
</>

MS. ESHA PATEL Page 20


Unit-3: Forms and Hooks in React.JS
);
}
Output:

React useRef Hook


The useRef Hook allows you to persist values between renders.

It can be used to store a mutable value that does not cause a re-render when updated.

It can be used to access a DOM element directly.

Does Not Cause Re-renders


If we tried to count how many times our application renders using the useState Hook, we would be
caught in an infinite loop since this Hook itself causes a re-render.

To avoid this, we can use the useRef Hook.

useRef() only returns one item. It returns an Object called current.

When we initialize useRef we set the initial value: useRef(0).

MS. ESHA PATEL Page 21


Unit-3: Forms and Hooks in React.JS
In react useref can be used to accessing DOM elements and tracking state changes.

The useRef Hook can also be used to keep track of previous state values.

This is because we are able to persist useRef values between renders.

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:

MS. ESHA PATEL Page 22


Unit-3: Forms and Hooks in React.JS

React useReducer Hook


The useReducer Hook is similar to the useState Hook.

It allows for custom state logic.

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.

The useReducer Hook returns the current stateand a dispatchmethod.

Example:
import { useReducer } from "react";
const initialTodos = [
{
id: 1,

MS. ESHA PATEL Page 23


Unit-3: Forms and Hooks in React.JS
title: "Todo 1",
complete: false,
},
{
id: 2,
title: "Todo 2",
complete: false,
},
];
const reducer = (state, action) => {
switch (action.type) {
case "COMPLETE":
return state.map((todo) => {
if (todo.id === action.id) {
return { ...todo, complete: !todo.complete };
} else {
return todo;
}
});
default:
return state;
}
};
export default function Todos() {
const [todos, dispatch] = useReducer(reducer, initialTodos);

const handleComplete = (todo) => {


dispatch({ type: "COMPLETE", id: todo.id });

MS. ESHA PATEL Page 24


Unit-3: Forms and Hooks in React.JS
};
return (
<div>
{todos.map((todo) => (
<div key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.complete}
onChange={() => handleComplete(todo)}
/>
{todo.title}
</label>
</div>
))}
</div>
);
}
Output:

React useCallback Hook


The React useCallback Hook returns a memoized callback function.
MS. ESHA PATEL Page 25
Unit-3: Forms and Hooks in React.JS
Think of memoization as caching a value so that it does not need to be recalculated.

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.

This can improve performance.

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([]);

const increment = () => {


setCount((c) => c + 1);
};
const addTodo = useCallback(() => {
setTodos((t) => [...t, "New Todo"]);
}, [todos ]);

return (
<>
<Todos todos={todos} addTodo={addTodo} />
<hr />
<div>

MS. ESHA PATEL Page 26


Unit-3: Forms and Hooks in React.JS
Count: {count}
<button onClick={increment}>+</button>
</div>
</>
);
};
export default App;
Todos.js:
import { memo } from "react";
const Todos = ({ todos, addTodo }) => {
console.log("child render");
return (
<div>
<h2>My Todos</h2>
{todos.map((todo, index) => {
return <p key={index}>{todo}</p>;
})}
<button onClick={addTodo}>Add Todo</button>
</div>
);
};
export default memo(Todos);
Output:

MS. ESHA PATEL Page 27


Unit-3: Forms and Hooks in React.JS

React useMemo Hook


The React useMemo Hook returns a memoized value.

Think of memoization as caching a value so that it does not need to be recalculated.

The useMemo Hook only runs when one of its dependencies update.

This can improve performance.

The useMemo Hook can be used to keep expensive, resource intensive functions from needlessly
running.

In this example, we have an expensive function that runs on every render.

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.

We can wrap the expensive function call with useMemo.

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";

MS. ESHA PATEL Page 28


Unit-3: Forms and Hooks in React.JS
const App = () => {
const [count, setCount] = useState(0);
const [todos, setTodos] = useState([]);
const calculation = useMemo(() => expensiveCalculation(count), [count]);
const increment = () => {
setCount((c) => c + 1);
};
const addTodo = () => {
setTodos((t) => [...t, "New Todo"]);
};
return (
<div>
<div>
<h2>My Todos</h2>
{todos.map((todo, index) => {
return <p key={index}>{todo}</p>;
})}
<button onClick={addTodo}>Add Todo</button>
</div>
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
<h2>Expensive Calculation</h2>
{calculation}
</div>
</div>
);

MS. ESHA PATEL Page 29


Unit-3: Forms and Hooks in React.JS
};
const expensiveCalculation = (num) => {
console.log("Calculating...");
for (let i = 0; i < 1000000000; i++) {
num += 1;
}
return num;
};
export default App;
Output:

React Custom Hooks


Hooks are reusable functions.

When you have component logic that needs to be used by multiple components, we can extract that
logic to a custom Hook.

MS. ESHA PATEL Page 30


Unit-3: Forms and Hooks in React.JS
Custom Hooks start with "use". Example: useFetch.

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.

To learn more, check out the JavaScript Fetch API section.

Use the JSONPlaceholder service to fetch fake "todo" items and display the titles on the page:

Example:
App.js:

import { useState, useEffect } from "react";

const App = () => {

const [data, setData] = useState(null);

useEffect(() => {

fetch("https://jsonplaceholder.typicode.com/todos")

.then((res) => res.json())

.then((data) => setData(data));

}, []);

return (

<div>

{data &&

data.map((item) => {

return <p key={item.id}>{item.title}</p>;

MS. ESHA PATEL Page 31


Unit-3: Forms and Hooks in React.JS
})}

</div>

);

};

export default App;

The fetch logic may be needed in other components as well, so we will extract that into a custom
Hook.

Move the fetch logic to a new file to be used as a custom Hook:

Example:
useFetch.js:

import { useState, useEffect } from "react";

const useFetch = (url) => {

const [data, setData] = useState(null);

useEffect(() => {

fetch(url)

.then((res) => res.json())

.then((data) => setData(data));

}, [url]);

return [data];

};

export default useFetch;

App.js:

import React from 'react';


MS. ESHA PATEL Page 32
Unit-3: Forms and Hooks in React.JS
import useFetch from './useFetch';

const App = () => {

const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");

return (

<div>

{data &&

data.map((item) => {

return <p key={item.id}>{item.title}</p>;

})}

</div>

);

};

export default App;

Advantages
It provides reusability of the code.

Other benefits are same as the inbuilt hooks.

MS. ESHA PATEL Page 33

You might also like