Skip to content

Commit 081be9e

Browse files
committed
added solutions
1 parent 60c15dc commit 081be9e

File tree

7 files changed

+215
-0
lines changed

7 files changed

+215
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { useMemo, useState } from "react";
2+
3+
// In this assignment, your task is to create a component that performs an expensive calculation (finding the factorial) based on a user input.
4+
// Use useMemo to ensure that the calculation is only recomputed when the input changes, not on every render.
5+
6+
export function Assignment1() {
7+
const [input, setInput] = useState(0);
8+
9+
const expensiveValue = useMemo(() => {
10+
// Your solution starts here
11+
let value = 1;
12+
for (let i = 1; i <= input; i++) {
13+
value = value * i;
14+
}
15+
return value;
16+
}, [input]);
17+
18+
// Your solution ends here
19+
20+
return (
21+
<div>
22+
<input
23+
type="number"
24+
value={input}
25+
onChange={(e) => setInput(Number(e.target.value))}
26+
/>
27+
<p>Calculated Value: {expensiveValue}</p>
28+
</div>
29+
);
30+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import React, { useEffect, useMemo, useState } from "react";
2+
3+
// In this assignment, you will create a component that renders a large list of sentences and includes an input field for filtering these items.
4+
// 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).
5+
// You will learn something new here, specifically how you have to pass more than one value in the dependency array
6+
7+
const words = ["hi", "my", "name", "is", "for", "to", "random", "word" ];
8+
const TOTAL_LINES = 1000;
9+
const ALL_WORDS = [];
10+
for (let i = 0; i < TOTAL_LINES; i++) {
11+
let sentence = "";
12+
for (let j = 0; j < words.length; j++) {
13+
sentence += (words[Math.floor(words.length * Math.random())])
14+
sentence += " "
15+
}
16+
ALL_WORDS.push(sentence);
17+
}
18+
19+
export function Assignment2() {
20+
const [sentences, setSentences] = useState(ALL_WORDS);
21+
const [filter, setFilter] = useState("");
22+
23+
const filteredSentences = useMemo(() => {
24+
return sentences.filter(x => x.includes(filter));
25+
}, [sentences, filter])
26+
27+
return <div>
28+
<input type="text" onChange={(e) => {
29+
setFilter(e.target.value)
30+
}}></input>
31+
{filteredSentences.map(word => <div>
32+
{word}
33+
</div>)}
34+
</div>
35+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import React, { useState, useMemo } from 'react';
2+
// You have been given a list of items you shopped from the grocery store
3+
// You need to calculate the total amount of money you spent
4+
5+
export const Assignment3 = () => {
6+
const [items, setItems] = useState([
7+
{ name: 'Chocolates', value: 10 },
8+
{ name: 'Chips', value: 20 },
9+
{ name: 'Onion', value: 30 },
10+
{ name: 'Tomato', value: 30 },
11+
{ name: 'Tomato', value: 100 },
12+
// Add more items as needed
13+
]);
14+
15+
// Your code starts here
16+
// reducer
17+
const totalValue = useMemo(() => {
18+
let totalValue = 0;
19+
for (let i = 0; i < items.length; i++) {
20+
totalValue = totalValue + items[i].value;
21+
}
22+
return totalValue
23+
}, [items])
24+
25+
// Your code ends here
26+
return (
27+
<div>
28+
<ul>
29+
{items.map((item, index) => (
30+
<li key={index}>{item.name} - Price: ${item.value}</li>
31+
))}
32+
</ul>
33+
<p>Total Value: {totalValue}</p>
34+
</div>
35+
);
36+
};
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { memo, useCallback, useState } from "react";
2+
3+
// 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.
4+
5+
export function Assignment1() {
6+
const [count, setCount] = useState(0);
7+
8+
// Your code starts here
9+
const handleIncrement = useCallback(() => {
10+
setCount(function(currentCount) {
11+
return currentCount + 1;
12+
})
13+
}, [])
14+
15+
const handleDecrement = useCallback(() => {
16+
setCount(count => {
17+
return count - 1
18+
});
19+
}, []);
20+
// Your code ends here
21+
22+
return (
23+
<div>
24+
<p>Count: {count}</p>
25+
<CounterButtons onIncrement={handleIncrement} onDecrement={handleDecrement} />
26+
</div>
27+
);
28+
};
29+
30+
const CounterButtons = memo(({ onIncrement, onDecrement }) => (
31+
<div>
32+
<button onClick={onIncrement}>Increment</button>
33+
<button onClick={onDecrement}>Decrement</button>
34+
</div>
35+
));
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import React, { useState, useCallback } from 'react';
2+
3+
// 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.
4+
// Currently we only have inputText as a state variable and hence you might not see the benefits of
5+
// 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.
6+
7+
export function Assignment2() {
8+
const [inputText, setInputText] = useState('');
9+
10+
// Your code starts here
11+
const showAlert = useCallback(() => {
12+
alert(inputText);
13+
}, [inputText])
14+
// Your code ends here
15+
16+
return (
17+
<div>
18+
<input
19+
type="text"
20+
value={inputText}
21+
onChange={(e) => setInputText(e.target.value)}
22+
placeholder="Enter some text"
23+
/>
24+
<Alert showAlert={showAlert} />
25+
</div>
26+
);
27+
};
28+
29+
function Alert({showAlert}) {
30+
return <button onClick={showAlert}>Show Alert</button>
31+
}
32+
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { useRef } from "react";
2+
import { useEffect } from "react";
3+
4+
// 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.
5+
6+
export function Assignment1() {
7+
const inputRef = useRef();
8+
9+
useEffect(() => {
10+
inputRef.current.focus()
11+
}, [inputRef]);
12+
13+
const handleButtonClick = () => {
14+
inputRef.current.focus()
15+
};
16+
17+
return (
18+
<div>
19+
<input ref={inputRef} type="text" placeholder="Enter text here" />
20+
<button onClick={handleButtonClick}>Focus Input</button>
21+
</div>
22+
);
23+
};
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import React, { useState, useCallback } from 'react';
2+
import { useRef } from 'react';
3+
4+
// Create a component that tracks and displays the number of times it has been rendered.
5+
6+
export function Assignment2() {
7+
const [count, setCount] = useState(0);
8+
9+
const numberOfTimesReRendered = useRef(0);
10+
11+
const handleReRender = () => {
12+
// Update state to force re-render
13+
setCount(count + 1);
14+
};
15+
16+
numberOfTimesReRendered.current = numberOfTimesReRendered.current + 1;
17+
18+
return (
19+
<div>
20+
<p>This component has rendered {numberOfTimesReRendered.current} times.</p>
21+
<button onClick={handleReRender}>Force Re-render</button>
22+
</div>
23+
);
24+
};

0 commit comments

Comments
 (0)