React Challenges Flashcards
I have a list that i map on, on click I want to add new input item into that list…
state updating with the spread operator.
setItems([…items, input]);
setInput(“”);
spot the wrong things
- index{cryptocurrencyList.map((index, element) => {
<>
<td>{element.name}</td>
<td>{element.rate}</td>
<td>{numberCoin}</td>
</>
})}
In the map() function, the parameters are reversed. The correct order is:
array.map((element, index) => { … });
element refers to the current item in the array.
index is the position of the item.
spot the wrong things
- return issue{cryptocurrencyList.map((index, element) => {
<>
<td>{element.name}</td>
<td>{element.rate}</td>
<td>{numberCoin}</td>
</>
})}
Fragment Syntax Inside map()
You are trying to wrap multiple <td> elements using a React Fragment (<>…</>), which is correct. However, you forgot to return the Fragment from the map() function.
Corrected map syntax:
To fix this, add a return or use the implicit return syntax by removing {} in the arrow function.
spot the wrong things
- tr tag and key –> virtual dom hon!{cryptocurrencyList.map((index, element) => {
<>
<td>{element.name}</td>
<td>{element.rate}</td>
<td>{numberCoin}</td>
</>
})}
You cannot place multiple <tr> tags inside a single <tr> parent element. Instead, the map() function should create a separate <tr> for each item in cryptocurrencyList.
explain the error with jsx here:
{cryptocurrencyList.map((element, index) => (
<tr key={index}>
<td>{element.name}</td>
<td>1 USD= {exchangeAmount ? {element.rate} {element.code} : “”} </td>
<td>{exchangeAmount ? element.rate*exchangeAmount : (0.0000000.toFixed(8))}</td>
</tr>
))}
{element.rate} and {element.code} are being wrapped with extra curly braces. You don’t need {} inside JSX when you’re already inside curly braces.
how to put in jsx string+variable
1 USD = {exchangeAmount ? ${element.rate} ${element.code}
: “”}
Improper Return from Arrow Function:
1. explicit
2. implicit
give example
When using an arrow function with curly braces {}, you need to explicitly use the return keyword to return JSX. Alternatively, you can remove the braces to implicitly return JSX.
Option 1:
// With explicit return:
cryptocurrencyList.map((element, index) => {
return (
<React.Fragment key={index}>
<td>{element.name}</td>
<td>{element.rate}</td>
<td>{numberCoin}</td>
</React.Fragment>
);
});
// With implicit return:
cryptocurrencyList.map((element, index) => (
<React.Fragment key={index}>
<td>{element.name}</td>
<td>{element.rate}</td>
<td>{numberCoin}</td>
</React.Fragment>
));
Option 2:
// With implicit return:
cryptocurrencyList.map((element, index) => (
<React.Fragment key={index}>
<td>{element.name}</td>
<td>{element.rate}</td>
<td>{numberCoin}</td>
</React.Fragment>
));
react: mapping, key and virtual dom
you always need to use a key when mapping over a list of elements because React relies on the key to efficiently update the Virtual DOM and reconcile changes to the real DOM.
Why is key Needed?
The key helps React uniquely identify each element in a list. When the Virtual DOM is updated, React uses the key to determine:
Which elements have changed.
Which elements were added or removed.
avoid big components
glean extension to refactor
make small components, that can be reusable
avoid nesting components (having ponents inside other component in the same parent function –> memories issue if you dont need it)
avoid performance issue. avoid expesinve calculations.
with useMemo and useCallback (functions)
1 component per file is the best. avoid messy organization
each react component can have how many parent elements
- that is why you have fragment or div
page load in the browser. How to improve?
Code splitting: Use dynamic imports to load only necessary components, reducing the initial bundle size.
Optimize assets: Compress images and other static files to reduce their size and improve load times.
Minimize JavaScript: Minify and bundle JavaScript files to reduce their size and number of requests.
how to avoid prop drilling?
use redux
or use context api if is a simple global state
design patterns in react
summary : use custom hooks , use components for seperate all things , use inline func for basic things
React: Software Architecture | Server-side rendering basics. ej node.js and express
you need a server. t is a client-side library used to build the user interface that runs in the browser. so request can be handle
Node.js with Express: If you’re using Node.js as your server, your server-side logic would typically be in files like server.js or app.js.
2 examples of server side:
1- i have worked on
2- i will take a course on
Yes, in this setup, CherryPy replaces Node.js with Express as the backend server for your React app.
react components is a …
that returns..
and you can use..
javascript functions
that retuns jsx
you can use dynamic javascript in your jsx, such as states.
key props.. why we need it? and what is typically use for :)
is a unique value
to idenity component. we can use index
what is render? like how react knows when to render?
based on the virtual dom(document, object model) is the Tree!!
explain reconcilation
- react updates virtual dom
- react diffs. to see difference.
- use reconcilation to update dom
event handling. 3 most famous
onClick
onChange
onSubmit
what is a controlled component? dont be afraid. tell me your name, i will save it.
is when input from a textbox gets saved on a state, with e.target.value!
spot the error and explain it:
const Counter = () => {
const [counter, setCounter]= useState(0);
return (
<>
<label>Counter</label>
<h2>{counter}</h2>
<button onClick={setCounter(counter+1)}>Increase</button> <button onClick={setCounter(counter-1)}>Decrease</button> <button onClick={setCounter(0)}>Reset</button> </> ) };
When you write onClick={setCounter(counter + 1)}, the function executes immediately during rendering instead of being triggered on a button click.
<button onClick={() => setCounter(counter + 1)}>Increase</button>
2 ways of showing conditional a text on return. explain how to write it
{isVisible ? “Hide Text” : “Show Text”}
{isVisible && <h1>Our text</h1>}
arrow function or not for react handleClick, handleSubmit.. ect
clue… you have a param?
onClick: Requires an arrow function when you want to pass parameters or execute logic before the event handler. The arrow function ensures the handler isn’t executed immediately during render.
onSubmit: Doesn’t require an arrow function because React will automatically handle the event and call the handler when the form is submitted. It doesn’t execute the handler immediately on render.
Here, the arrow function is necessary because you’re calling handleClick(‘Hello’) with a parameter. Without the arrow function, React would try to execute handleClick(‘Hello’) immediately during the render phase, which is not what you want.
write a callback function
const hand = useCallback (() => {}, [])
handleSubmit, what triggers the default behaviour in a form?
onSubmit Without Preventing Default:
The onSubmit event in React forms needs to call event.preventDefault() to prevent the default form submission behavior (reloading the page).
is input a self or double closing element?
<input></input> elements should be self-closing. It’s invalid to wrap children inside an <input></input> tag.
what arr method to use when i want to remove something (a value) from an array?
Use reduce for calculations or transformations (e.g., sums, counts).
Use filter to selectively remove or keep elements based on a condition.
reduce and accumulator meaning..
const words = [“Hello”, “world”, “with”, “reduce”];
// Combine all words into a single sentence
const sentence = words.reduce((acc, word) => acc + “ “ + word, “”);
console.log(sentence);
// Output: “Hello world with reduce”
list item. when i have more than one item with same index in a <li>. ex.
<>
<li key={index}>{item.name}</li>
<li key={index}>{item.id}</li>
</>
<li key={item.id}>
<div>{item.name}</div>
<div>{item.id}</div>
</li>
what is called doing this to props {}
const MyComponent = ({ name, age }) => {
return <p>{name} is {age} years old.</p>;
};
Destructure Props
contains is not a valid string method. which one should i use?
includes()
I need to check if its an array, case is not i go for ternary conditional.
{result.lenght > 0 ? result.map((item, index) => <li key={index}>{item}</li>) : result}
{Array.isArray(result) ? (
result.map((item, index) => <li key={index}>{item}</li>)
) : (
result
why is this wrong? thin of asyncronic
const onNextClick = () => {
setPageNumber(pageNumber + 1);
onPageChange(pageNumber);
};
const onNextClick = () => {
if (pageNumber < totalPages) {
const newPageNumber = pageNumber + 1;
setPageNumber(newPageNumber);
onPageChange(newPageNumber);
}
};
Since setPageNumber is asynchronous, the value of pageNumber you are passing to onPageChange is still the old value when the buttons are clicked. You can update onPageChange after setting the new page number, ensuring the correct page number is passed.
como hacer un get y un set del localStorage?
localStorage.getITem(“theme”)
localStorage.setItem(“theme”, theme);
is localStorage like cookies?
similar.
localStorage: Ideal for storing non-sensitive data that you want to persist for the duration of the session or across sessions
Yes, localStorage data is saved on the user’s computer in the browser. Specifically, it is stored in a special location within the browser’s storage system called the Web Storage API.
recordar expresion regular:
replace(/[^a-z0-9]/gi, ‘’)
[^a-z0-9]
a-z: Esto significa todas las letras minúsculas de la a a la z.
0-9: Esto incluye todos los dígitos del 0 al 9.
El ^ dentro de los corchetes significa “no”. Entonces, [^a-z0-9] significa “cualquier carácter que no sea una letra o un número”.
g: Esto indica que la expresión regular debe ser aplicada de manera global (es decir, en toda la cadena, no solo en la primera coincidencia).
i: Esto hace que la búsqueda no distinga entre mayúsculas y minúsculas.
’’: El segundo parámetro de replace() es lo que usas para reemplazar los caracteres que coinciden con la expresión regular. En este caso, estamos eliminando esos caracteres no alfanuméricos, por lo que usamos una cadena vacía (‘’).
que es una expresion regular
Una expresión regular (a menudo abreviada como regex).
Se utiliza para buscar, coincidir o reemplazar texto dentro de cadenas de caracteres según un patrón específico.
create a usecallback, to add a task to.
tell me how to write useCallback
and how to use localStorage to set the item
const getTask = localStorage.get(“tasks”);
const [task, setTask] = useState(getTask || []);
const [newTask, setNewTask] = useState(“”);
const addTask = useCallback((newTask) => {
const newTaskDef = […task, newTask];
setTask(newTaskDef);
localStorage.setItem(“tasks”, JSON.stringify(newTaskDef));
}, [task]);
const addTask = useCallback(() => {
// Add task logic
}, [task, newTask]);
built-in JavaScript function
clearTimeout() is used to cancel a timeout previously established by setTimeout().
Give an example…
tip: searchBar
const [text, setText] = useState();
const [debouncedText, setDebouncedText] = useState(“”);
useEffect (() => { const timer = setTimeout(() => { setDebouncedText(text); }, 500) return () => { clearTimeout(timer); } }, [text]);
Axios service call example in component:
useEffect(() => {
if (debouncedText) {
setIsLoading(true);
setIsError(false);
fetchResults(debouncedText) .then((response) => { setResults(response.data); }) .catch((error) => { console.error('Error fetching data:', error); setIsError(true); }) .finally(() => { setIsLoading(false); }); } else { setResults([]); }
how to render a filteredItems list? how to filter that. give me the const filteredItems=
const filteredItems = items.filter(item => item.toLowerCase().includes(search.toLowerCase()));
filetered items should i use filter or maps. and why?
const filteredItems = items.map(item => item.includes(search)); // This returns an array of booleans, not items
console.log(filteredItems);
// Output: [true, false, false, false, false] (Not the filtered items!)
what is redux (2)
Redux is a state management library commonly used in JavaScript
-centralized place to store state
how to change state in redux?
To change the state, an action is dispatched
what files i need in redux?
- store, that has the “reducers”
- provider wrap around app
- slice, is data in store with reducers (actions)
what is in store file in redux?
you have your reducer, with actions you import from your “slice” file.
what is the slice file?
the sliice file is where you create your slice, meaning you create your global state.
And you decide on reducers, meaning functions that can change your state.
what is a dispatch and where i use it?
dispatch trigers the action/reducer in your slice file.
what is the useSelector for?
to access to state stored in redux, from a component.
const todos = useSelector((state) => state.todos);
redux flow
USER CLICK –> DISPATCH –> ACTION –> TRIGGERS REDUCER (slice) –> STORE (in store file)
firebase
Firebase acts like a backend-as-a-service (BaaS)
database management, authentication, cloud storage, serverless functions
Realtime Database and Firestore: Cloud-hosted NoSQL databases that store
-can do access control
-zero latency in data updates (you can configure in you files)
use memo vs useCallback
When you want to memoize a value (such as a computed value or an object/array) that doesn’t need to be recalculated unless certain dependencies change.
useCallback is used to memoize a function (like event handlers or callbacks) so that it doesn’t get recreated on every render. Any ONCLICK
why this is wrong?
const decreaseCounter = useMemo (() => {
setCounter(counter-1);
}, [counter]);
useCallback is used to memoize a function (like event handlers or callbacks) so that it doesn’t get recreated on every render. Any ONCLICK
Remeber, it gets trigger!! with same data!
Task app improvoments:
const addTask = useCallback(
() => {
setTasks(…tasks, {id: 5, name: name, description: description});
},
[tasks]
);
First huge error –> setTasks([…tasks, newTask]);
Task app improvoments for ADD:
const addTask = useCallback(() => {
const newTask = { id: Date.now(), // Use timestamp for a unique ID name: name, description: description, }; setName(""); // Clear input fields after adding setDescription(""); }, [tasks, name, description, editMode]);
const addTask = useCallback(() => {
if (!name || !description) {
alert(“Both fields are required!”);
return;
}
const newTask = { id: Date.now(), // Use timestamp for a unique ID name: name, description: description, };
Task app improvoments for ADD:
Edit btn
const [tasks, setTasks] = useState([
{ id: 1, name: “Task One”, description: “blabla” },
]);
<button onClick={() => editTask(item.id)}>Edit</button>
You add it with other btn call Update.
const editTask = useCallback(
(taskId) => {
const taskToEdit = tasks.find((item) => item.id === taskId);
setName(taskToEdit.name);
setDescription(taskToEdit.description);
setEditMode(taskId); // Enable edit mode with the task ID
},
[tasks]
);