Skip to content

Commit

Permalink
added solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
hkirat committed Jan 13, 2024
1 parent 60c15dc commit 081be9e
Show file tree
Hide file tree
Showing 7 changed files with 215 additions and 0 deletions.
30 changes: 30 additions & 0 deletions week-6/solutions/1/components/Assignment1.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useMemo, useState } from "react";

// In this assignment, your task is to create a component that performs an expensive calculation (finding the factorial) based on a user input.
// Use useMemo to ensure that the calculation is only recomputed when the input changes, not on every render.

export function Assignment1() {
const [input, setInput] = useState(0);

const expensiveValue = useMemo(() => {
// Your solution starts here
let value = 1;
for (let i = 1; i <= input; i++) {
value = value * i;
}
return value;
}, [input]);

// Your solution ends here

return (
<div>
<input
type="number"
value={input}
onChange={(e) => setInput(Number(e.target.value))}
/>
<p>Calculated Value: {expensiveValue}</p>
</div>
);
}
35 changes: 35 additions & 0 deletions week-6/solutions/1/components/Assignment2.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React, { useEffect, useMemo, useState } from "react";

// In this assignment, you will create a component that renders a large list of sentences and includes an input field for filtering these items.
// The goal is to use useMemo to optimize the filtering process, ensuring the list is only re-calculated when necessary (e.g., when the filter criteria changes).
// You will learn something new here, specifically how you have to pass more than one value in the dependency array

const words = ["hi", "my", "name", "is", "for", "to", "random", "word" ];
const TOTAL_LINES = 1000;
const ALL_WORDS = [];
for (let i = 0; i < TOTAL_LINES; i++) {
let sentence = "";
for (let j = 0; j < words.length; j++) {
sentence += (words[Math.floor(words.length * Math.random())])
sentence += " "
}
ALL_WORDS.push(sentence);
}

export function Assignment2() {
const [sentences, setSentences] = useState(ALL_WORDS);
const [filter, setFilter] = useState("");

const filteredSentences = useMemo(() => {
return sentences.filter(x => x.includes(filter));
}, [sentences, filter])

return <div>
<input type="text" onChange={(e) => {
setFilter(e.target.value)
}}></input>
{filteredSentences.map(word => <div>
{word}
</div>)}
</div>
}
36 changes: 36 additions & 0 deletions week-6/solutions/1/components/Assignment3.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React, { useState, useMemo } from 'react';
// You have been given a list of items you shopped from the grocery store
// You need to calculate the total amount of money you spent

export const Assignment3 = () => {
const [items, setItems] = useState([
{ name: 'Chocolates', value: 10 },
{ name: 'Chips', value: 20 },
{ name: 'Onion', value: 30 },
{ name: 'Tomato', value: 30 },
{ name: 'Tomato', value: 100 },
// Add more items as needed
]);

// Your code starts here
// reducer
const totalValue = useMemo(() => {
let totalValue = 0;
for (let i = 0; i < items.length; i++) {
totalValue = totalValue + items[i].value;
}
return totalValue
}, [items])

// Your code ends here
return (
<div>
<ul>
{items.map((item, index) => (
<li key={index}>{item.name} - Price: ${item.value}</li>
))}
</ul>
<p>Total Value: {totalValue}</p>
</div>
);
};
35 changes: 35 additions & 0 deletions week-6/solutions/2/components/Assignment1.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { memo, useCallback, useState } from "react";

// Create a counter component with increment and decrement functions. Pass these functions to a child component which has buttons to perform the increment and decrement actions. Use useCallback to ensure that these functions are not recreated on every render.

export function Assignment1() {
const [count, setCount] = useState(0);

// Your code starts here
const handleIncrement = useCallback(() => {
setCount(function(currentCount) {
return currentCount + 1;
})
}, [])

const handleDecrement = useCallback(() => {
setCount(count => {
return count - 1
});
}, []);
// Your code ends here

return (
<div>
<p>Count: {count}</p>
<CounterButtons onIncrement={handleIncrement} onDecrement={handleDecrement} />
</div>
);
};

const CounterButtons = memo(({ onIncrement, onDecrement }) => (
<div>
<button onClick={onIncrement}>Increment</button>
<button onClick={onDecrement}>Decrement</button>
</div>
));
32 changes: 32 additions & 0 deletions week-6/solutions/2/components/Assignment2.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import React, { useState, useCallback } from 'react';

// Create a component with a text input field and a button. The goal is to display an alert with the text entered when the button is clicked. Use useCallback to memoize the event handler function that triggers the alert, ensuring it's not recreated on every render.
// Currently we only have inputText as a state variable and hence you might not see the benefits of
// useCallback. We're also not passing it down to another component as a prop which is another reason for you to not see it's benefits immedietely.

export function Assignment2() {
const [inputText, setInputText] = useState('');

// Your code starts here
const showAlert = useCallback(() => {
alert(inputText);
}, [inputText])
// Your code ends here

return (
<div>
<input
type="text"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="Enter some text"
/>
<Alert showAlert={showAlert} />
</div>
);
};

function Alert({showAlert}) {
return <button onClick={showAlert}>Show Alert</button>
}

23 changes: 23 additions & 0 deletions week-6/solutions/3/components/Assignment1.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useRef } from "react";
import { useEffect } from "react";

// Create a component with a text input field and a button. When the component mounts or the button is clicked, automatically focus the text input field using useRef.

export function Assignment1() {
const inputRef = useRef();

useEffect(() => {
inputRef.current.focus()
}, [inputRef]);

const handleButtonClick = () => {
inputRef.current.focus()
};

return (
<div>
<input ref={inputRef} type="text" placeholder="Enter text here" />
<button onClick={handleButtonClick}>Focus Input</button>
</div>
);
};
24 changes: 24 additions & 0 deletions week-6/solutions/3/components/Assignment2.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import React, { useState, useCallback } from 'react';
import { useRef } from 'react';

// Create a component that tracks and displays the number of times it has been rendered.

export function Assignment2() {
const [count, setCount] = useState(0);

const numberOfTimesReRendered = useRef(0);

const handleReRender = () => {
// Update state to force re-render
setCount(count + 1);
};

numberOfTimesReRendered.current = numberOfTimesReRendered.current + 1;

return (
<div>
<p>This component has rendered {numberOfTimesReRendered.current} times.</p>
<button onClick={handleReRender}>Force Re-render</button>
</div>
);
};

0 comments on commit 081be9e

Please sign in to comment.