0% found this document useful (0 votes)
4 views9 pages

Unit 4 React Components

The document provides an overview of React Hooks, which allow functional components to utilize state and lifecycle features, simplifying code maintenance. It details various types of hooks, such as State, Context, Ref, Effect, Performance, and Resource Hooks, along with their usage examples. Additionally, it outlines the differences between class components and hooks, installation requirements, and rules for using hooks in React applications.

Uploaded by

Uma Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Unit 4 React Components

The document provides an overview of React Hooks, which allow functional components to utilize state and lifecycle features, simplifying code maintenance. It details various types of hooks, such as State, Context, Ref, Effect, Performance, and Resource Hooks, along with their usage examples. Additionally, it outlines the differences between class components and hooks, installation requirements, and rules for using hooks in React applications.

Uploaded by

Uma Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

React Components & Hooks:

React Hooks are functions that enable functional components to use React
state and lifecycle features. They eliminate the need for class
components, making code cleaner and easier to maintain.

Types of React Hooks

1. State Hooks

State Hooks like useState allows functional components to manage local


state.

import React, { useState } from "react";

function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() =>
setCount(count + 1)}>Increment</button>
</div>
);
}

export default Counter;

 useState initializes the count variable with 0 and provides a method


setCount to update it.

 Clicking the button updates the state using the setCount function.

2. Context Hooks

Context Hooks like useContext enable functional components to access


the React Context API and share data across the component tree.

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

const Contexts = createContext("light");

function Theme() {
const theme = useContext(Contexts);
return <h1>Theme: {theme}</h1>;
}

export default function App() {


return (
<Contexts.Provider value="dark">
<Theme />
</Contexts.Provider>
);
}
 The Theme Context provides a value (“dark”) accessible via
useContext in DisplayTheme.

 This eliminates the need to pass props manually down the


component tree.

3. Ref Hooks

Ref Hooks like useRef provide access to DOM nodes or persist values
without causing re-renders.

import React, { useRef } from "react";

function Focus() {
const input = useRef();

const focus = () => input.current.focus();

return (
<div>
<input ref={input} type="text" />
<button onClick={focus}>Focus</button>
</div>
);
}

export default Focus;

 useRef stores a reference to the input element, allowing the focus


function to programmatically set focus on it.

 Updating inputRef does not cause the component to re-render.

4. Effect Hooks

Effect Hooks like useEffect handle side effects like fetching data,
subscriptions, and DOM manipulation.
import React, { useEffect, useState } from "react";

function Timer() {
const [seconds, setSeconds] = useState(0);

useEffect(() => {
const interval = setInterval(() =>
setSeconds((s) => s + 1), 1000);
return () => clearInterval(interval);
}, []);

return <h1>Time: {seconds}s</h1>;


}

export default Timer;

 The useEffect hook starts an interval to update the seconds state


every second.

 The cleanup function ensures the interval is cleared when the


component unmounts.

5. Performance Hooks

Performance Hooks like useMemo and useCallback optimize rendering by


memoizing values or functions.

 useMemo: Returns a memoized value to avoid expensive


calculations on every render.

 useCallback: Returns a memoized version of a callback function.

import React, { useMemo } from "react";

function ExpCal({ num }) {


const compute = useMemo(() => num * 2, [num]);
return <h1>Result: {compute}</h1>;
}
 useMemo caches the computed value (num * 2), recalculating it
only when num changes.

 This prevents unnecessary calculations on every render.

6. Resource Hooks

These include useFetch or custom hooks for fetching and managing


external resources.
function useFetch(url) {
const [data, setData] = useState(null);

useEffect(() => {
fetch(url)
.then((response) => response.json())
.then((data) => setData(data));
}, [url]);

return data;
}
 useFetch is a custom hook for fetching data from a given URL.

 It uses useEffect to fetch data when the URL changes and updates
the data state.

Step 1: Install Node.js

 Download and install Node.js

Step 2: Create a React App

Run the following commands in your terminal:

npx create-react-app my-app

cd my-app

npm start

Step 3: Replace Code in App.js

Open src/App.js and replace its content with your code.

Your app will now run at http://localhost:3000

State And Props


State
 The state is an updatable structure that is used to contain data or
information about the component and can change over time.
 The change in state can happen as a response to user action or system
event.
 It is the heart of the react component which determines the behavior
of the component and how it will render.
 A state must be kept as simple as possible. It represents the
component's local state or information.
 It can only be accessed or modified inside the component or by the
component directly.

Props
 Props are read-only components. It is an object which stores the value
of attributes of a tag and work similar to the HTML attributes.
 It allows passing data from one component to other components.
 It is similar to function arguments and can be passed to the component
the same way as arguments passed in a

Hooks:
React Hooks
 Hooks are the new feature introduced in the React 16.8
version. It allows you to use state and other React features
without writing a class. Hooks are the functions which
"hook into" React state and lifecycle features from
function components. It does not work inside classes.
 Hooks are backward-compatible, which means it does not
contain any breaking changes. Also, it does not replace
your knowledge of React concepts.
When to use a Hooks
If you write a function component, and then you want to add
some state to it, previously you do this by converting it to a
class. But, now you can do it by using a Hook inside the existing
function component.
Types of React Hooks

Rules of Hooks
Hooks are similar to JavaScript functions, but you need to follow
these two rules when using them. Hooks rule ensures that all
the stateful logic in a component is visible in its source code.
These rules are:
1. Only call Hooks at the top level
Do not call Hooks inside loops, conditions, or nested functions.
Hooks should always be used at the top level of the React
functions. This rule ensures that Hooks are called in the same
order each time a components renders.
2. Only call Hooks from React functions
You cannot call Hooks from regular JavaScript functions.
Instead, you can call Hooks from React function components.
Hooks can also be called from custom Hooks.
Pre-requisites for React Hooks
1. Node version 6 or above
2. NPM version 5.2 or above
3. Create-react-app tool for running the React App

React Hooks Installation


To use React Hooks, we need to run the following commands:

4. $ npm install [email protected] --save


5. $ npm install [email protected] --save
The above command will install the latest React and React-DOM alpha
versions which support React Hooks. Make sure the package.json file lists
the React and React-DOM dependencies as given below.

6. "react": "^16.8.0-alpha.1",
7. "react-dom": "^16.8.0-alpha.1",

Example App.js
import React, { useState } from "react";

import ReactDOM from "react-dom/client";

function FavoriteColor() {

const [color, setColor] = useState("red");


return (

<>

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

</>

);

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<FavoriteColor />);
Index.js
import React from "react";
import ReactDOM from "react-dom/client";
import FavoriteColor from "./App"; // Import
FavoriteColor

const root =
ReactDOM.createRoot(document.getElementById("root")
);
root.render(<FavoriteColor />);

output

Difference Between Hooks and Class Components.

Class Components React Hooks

Defined with
Defined with the class keyword regular
and extends React.Component JavaScript
functions

Use useState()
Use setState() method
hook

Have lifecycle methods Use useEffect()


Class Components React Hooks

like componentDidMount(), component


hook
DidUpdate(), etc.

Create custom
Utilize higher-order components and
hooks for code
render props for code reuse
reuse

Promote a more
functional
Can become complex due to managing
approach,
state, lifecycle methods, etc.
leading to
simpler code

Designed to be
Can have performance overhead due to more efficient
lifecycle methods and improve
performance

You might also like