0% found this document useful (0 votes)
3 views10 pages

Ia 2 Solutions

Uploaded by

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

Ia 2 Solutions

Uploaded by

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

a. How can state be managed in functional components using the useReducer hook?

Demonstrate with an example implementing a simple counter.

The useReducer hook is used for managing complex state logic in functional components. It
is an alternative to useState and is particularly useful when state transitions involve multiple
sub-states or actions.

Example: import React, { useReducer } from "react";

const initialState = { count: 0 };

function reducer(state, action) {

switch (action.type) {

case "increment":

return { count: state.count + 1 };

case "decrement":

return { count: state.count - 1 };

case "reset":

return initialState;

default:

throw new Error("Unknown action type");

function Counter() {

const [state, dispatch] = useReducer(reducer, initialState);

return (

<div>

<p>Count: {state.count}</p>

<button onClick={() => dispatch({ type: "increment" })}>Increment</button>

<button onClick={() => dispatch({ type: "decrement" })}>Decrement</button>

<button onClick={() => dispatch({ type: "reset" })}>Reset</button> </div> );}


b. Explain the lifecycle phases of a React Class Component. Compare this with the
useEffect hook's behavior in functional components.

Lifecycle Phases in Class Components:

1. Mounting: constructor, componentDidMount.


2. Updating: shouldComponentUpdate, componentDidUpdate.
3. Unmounting: componentWillUnmount.

Comparison with useEffect:

 In functional components, useEffect combines the behavior of componentDidMount,


componentDidUpdate, and componentWillUnmount.
 The dependency array in useEffect determines when it runs, providing flexibility to target
specific phases.

Example: import React, { useEffect, useState } from "react";

function Example() {

const [count, setCount] = useState(0);

useEffect(() => {

console.log("Component mounted or updated");

return () => {

console.log("Cleanup on unmount");

};

}, [count]); // Runs only when count changes

return <button onClick={() => setCount(count + 1)}>Click Me</button>;

}
c. Build a React app with a Toggle Button that changes the theme (light/dark). Describe
how the toggle state is managed.

Example: import React, { useState } from "react";

function ThemeToggle() {

const [isDark, setIsDark] = useState(false);

const toggleTheme = () => setIsDark((prevTheme) => prevTheme);

return (

<div style={{ background: isDark ? "#333" : "#fff", color: isDark ? "#fff" : "#000", height:
"100vh" }}>

<button onClick={toggleTheme}>

Switch to {isDark ? "Light" : "Dark"} Theme

</button>

</div>

);}

Explanation: The state isDark determines the current theme. The toggleTheme function toggles
this state using setState.
D. Discuss the usage of the useEffect hook in managing API calls in functional
components. Why is dependency management crucial in this hook?

 useEffect is used to fetch data from APIs during the component lifecycle (e.g., after
the component mounts).
 Dependency management ensures the effect runs only when specific values change,
avoiding infinite loops or redundant calls.

Example: import React, { useEffect, useState } from "react";

function FetchData() {

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

useEffect(() => {

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

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

}, []); // Empty dependency array ensures this runs only once

return (

<ul>

{data.map((item) => (

<li key={item.id}>{item.title}</li>

))}

</ul>

);

}
e. Write a React application that uses the Modal component and a button that toggles
the modal visibility. Explain how the modal state is managed.

Example: import React, { useState } from "react";

function Modal({ isVisible, onClose }) {

if (!isVisible) return null;

return (

<div className="modal">

<div className="modal-content">

<h2>Modal Title</h2>

<p>This is the modal content</p>

<button onClick={onClose}>Close</button>

</div>

</div>

);

function App() {

const [isModalVisible, setModalVisible] = useState(false);

return (

<div>

<button onClick={() => setModalVisible(true)}>Open Modal</button>

<Modal isVisible={isModalVisible} onClose={() => setModalVisible(false)} />

</div>);}

Explanation: The isModalVisible state is used to toggle the visibility of the modal. onClose
updates the state to hide the modal.
Part B (2 × 9 = 18 Marks)

a. Create a functional React component that uses useState and useEffect hooks to
display a list of items fetched from an API. Explain how data is fetched and state is
updated.

Example: function ItemList() {

const [items, setItems] = useState([]);

useEffect(() => {

async function fetchData() {

const response = await fetch("https://api.example.com/items");

const data = await response.json();

setItems(data);

fetchData();

}, []); // Runs only once on mount

return (

<ul>

{items.map((item) => (

<li key={item.id}>{item.name}</li>

))}

</ul>

);

Explanation: The useEffect hook fetches data from the API once the component mounts,
and the useState hook stores the fetched data.
b. Design a React component that uses useState to manage form input data and useRef
to focus an input field. Explain when useRef would be preferable to useState.

Example: import React, { useState, useRef } from "react";

function Form() {

const [inputValue, setInputValue] = useState("");

const inputRef = useRef(null);

const handleFocus = () => {

inputRef.current.focus();

};

return (

<div>

<input

ref={inputRef}

value={inputValue}

onChange={(e) => setInputValue(e.target.value)}

/>

<button onClick={handleFocus}>Focus Input</button>

</div>

);

Explanation: useRef is used for direct DOM manipulation (focusing the input field), while
useState tracks the input value.
c. Develop a React app that uses useReducer for complex state management and
useCallback to handle memoized functions for optimizing performance.

Example: import React, { useReducer, useCallback } from "react";

function App() {

const initialState = { count: 0 };

const reducer = (state, action) => {

switch (action.type) {

case "increment":

return { count: state.count + 1 };

case "decrement":

return { count: state.count - 1 };

default:

return state;

};

const [state, dispatch] = useReducer(reducer, initialState);

const handleIncrement = useCallback(() => dispatch({ type: "increment" }), []);

const handleDecrement = useCallback(() => dispatch({ type: "decrement" }), []);

return (

<div>

<p>Count: {state.count}</p>

<button onClick={handleIncrement}>Increment</button>

<button onClick={handleDecrement}>Decrement</button>

</div>

);

}
Part C (1 × 12 = 12 Marks)

a. Design a simple to-do list application in React where users can add, edit, and delete
tasks. Implement the following features:

import React, { useState, useEffect, useRef } from "react";

function TodoApp() {

const [tasks, setTasks] = useState(() =>


JSON.parse(localStorage.getItem("tasks")) || []);

const inputRef = useRef(null);

useEffect(() => {

localStorage.setItem("tasks", JSON.stringify(tasks));

}, [tasks]);

const addTask = () => {

const task = inputRef.current.value;

if (task) {

setTasks([...tasks, task]);

inputRef.current.value = "";

};

const deleteTask = (index) => {

setTasks(tasks.filter((_, i) => i !== index));

};

return (

<div>

<input ref={inputRef} type="text" placeholder="New task" />


<button onClick={addTask}>Add Task</button>

<ul>

{tasks.map((task, index) => (

<li key={index}>

{task}

<button onClick={() => deleteTask(index)}>Delete</button>

</li>

))}

</ul>

</div>

);

Purpose of hooks:

 useState: Manages the task list.


 useEffect: Persists tasks to local storage.
 useRef: Focuses the input field for better user experience.

You might also like