React Challenges Flashcards

1
Q

I have a list that i map on, on click I want to add new input item into that list…

A

state updating with the spread operator.

setItems([…items, input]);
setInput(“”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

spot the wrong things

  1. index{cryptocurrencyList.map((index, element) => {
    <>
    <td>{element.name}</td>
    <td>{element.rate}</td>
    <td>{numberCoin}</td>
    </>
    })}
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

spot the wrong things

  1. return issue{cryptocurrencyList.map((index, element) => {
    <>
    <td>{element.name}</td>
    <td>{element.rate}</td>
    <td>{numberCoin}</td>
    </>
    })}
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

spot the wrong things

  1. tr tag and key –> virtual dom hon!{cryptocurrencyList.map((index, element) => {
    <>
    <td>{element.name}</td>
    <td>{element.rate}</td>
    <td>{numberCoin}</td>
    </>
    })}
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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

A

{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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

how to put in jsx string+variable

A

1 USD = {exchangeAmount ? ${element.rate} ${element.code} : “”}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Improper Return from Arrow Function:
1. explicit
2. implicit

give example

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

react: mapping, key and virtual dom

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

avoid big components

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

each react component can have how many parent elements

A
  1. that is why you have fragment or div
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

page load in the browser. How to improve?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

how to avoid prop drilling?

A

use redux
or use context api if is a simple global state

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

design patterns in react

A

summary : use custom hooks , use components for seperate all things , use inline func for basic things

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

React: Software Architecture | Server-side rendering basics. ej node.js and express

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

2 examples of server side:
1- i have worked on
2- i will take a course on

A

Yes, in this setup, CherryPy replaces Node.js with Express as the backend server for your React app.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

react components is a …
that returns..

and you can use..

A

javascript functions
that retuns jsx

you can use dynamic javascript in your jsx, such as states.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

key props.. why we need it? and what is typically use for :)

A

is a unique value
to idenity component. we can use index

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

what is render? like how react knows when to render?

A

based on the virtual dom(document, object model) is the Tree!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

explain reconcilation

A
  1. react updates virtual dom
  2. react diffs. to see difference.
  3. use reconcilation to update dom
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

event handling. 3 most famous

A

onClick
onChange
onSubmit

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

what is a controlled component? dont be afraid. tell me your name, i will save it.

A

is when input from a textbox gets saved on a state, with e.target.value!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

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>
    </>
) };
A

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>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

2 ways of showing conditional a text on return. explain how to write it

A

{isVisible ? “Hide Text” : “Show Text”}
{isVisible && <h1>Our text</h1>}

24
Q

arrow function or not for react handleClick, handleSubmit.. ect

clue… you have a param?

A

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.

25
Q

write a callback function

A

const hand = useCallback (() => {}, [])

26
Q

handleSubmit, what triggers the default behaviour in a form?

A

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

27
Q

is input a self or double closing element?

A

<input></input> elements should be self-closing. It’s invalid to wrap children inside an <input></input> tag.

28
Q

what arr method to use when i want to remove something (a value) from an array?

A

Use reduce for calculations or transformations (e.g., sums, counts).
Use filter to selectively remove or keep elements based on a condition.

29
Q

reduce and accumulator meaning..

A

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”

30
Q

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

A

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

31
Q

what is called doing this to props {}

const MyComponent = ({ name, age }) => {
return <p>{name} is {age} years old.</p>;
};

A

Destructure Props

32
Q

contains is not a valid string method. which one should i use?

A

includes()

33
Q

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}

A

{Array.isArray(result) ? (
result.map((item, index) => <li key={index}>{item}</li>)
) : (
result

34
Q

why is this wrong? thin of asyncronic

const onNextClick = () => {
setPageNumber(pageNumber + 1);
onPageChange(pageNumber);
};

A

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.

35
Q

como hacer un get y un set del localStorage?

A

localStorage.getITem(“theme”)
localStorage.setItem(“theme”, theme);

36
Q

is localStorage like cookies?

A

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.

37
Q

recordar expresion regular:
replace(/[^a-z0-9]/gi, ‘’)

A

[^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 (‘’).

38
Q

que es una expresion regular

A

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.

39
Q

create a usecallback, to add a task to.
tell me how to write useCallback
and how to use localStorage to set the item

A

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]);

40
Q

built-in JavaScript function

clearTimeout() is used to cancel a timeout previously established by setTimeout().

Give an example…
tip: searchBar

A

const [text, setText] = useState();
const [debouncedText, setDebouncedText] = useState(“”);

useEffect (() => {

    const timer = setTimeout(() => {
        setDebouncedText(text);
    }, 500)

    return () => {
        clearTimeout(timer);
    }
}, [text]);
41
Q

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([]);
    }
42
Q

how to render a filteredItems list? how to filter that. give me the const filteredItems=

A

const filteredItems = items.filter(item => item.toLowerCase().includes(search.toLowerCase()));

43
Q

filetered items should i use filter or maps. and why?

A

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

44
Q

what is redux (2)

A

Redux is a state management library commonly used in JavaScript
-centralized place to store state

45
Q

how to change state in redux?

A

To change the state, an action is dispatched

46
Q

what files i need in redux?

A
  1. store, that has the “reducers”
  2. provider wrap around app
  3. slice, is data in store with reducers (actions)
47
Q

what is in store file in redux?

A

you have your reducer, with actions you import from your “slice” file.

48
Q

what is the slice file?

A

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.

49
Q

what is a dispatch and where i use it?

A

dispatch trigers the action/reducer in your slice file.

50
Q

what is the useSelector for?

A

to access to state stored in redux, from a component.
const todos = useSelector((state) => state.todos);

51
Q

redux flow

A

USER CLICK –> DISPATCH –> ACTION –> TRIGGERS REDUCER (slice) –> STORE (in store file)

52
Q

firebase

A

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)

53
Q

use memo vs useCallback

A

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

54
Q

why this is wrong?

const decreaseCounter = useMemo (() => {
setCounter(counter-1);
}, [counter]);

A

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!

55
Q

Task app improvoments:

const addTask = useCallback(
() => {
setTasks(…tasks, {id: 5, name: name, description: description});
},
[tasks]
);

A

First huge error –> setTasks([…tasks, newTask]);

56
Q

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]);
A

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,
};
57
Q

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.

A

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]
);