React Flashcards

1
Q

HTTP is a stateless protocol. What does it meand?

A

the server does not keep any data (state) between two requests.

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

What is DOM

A

Document Object Model is an Application Programming Interface (API) which enables programmatic modification of the element trees corresponding to web-pages.

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

What is Node.js

A

JavaScript runtime environment based on Google’s Chrome V8 JavaScript engine and works practically anywhere - from servers to mobile phones.

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

Name main One characteristic functional programming paradigm that is used in React. Which methods are used to follow this rule?

A

immutable data structures
concat method is used, which does not add the item to the array , but creates a new array in which the content of the old array and the new item are both included.
~~~
const t2 = t.concat(5)
~~~

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

Difference between function declare type
~~~
function product(a, b) {
return a * b
}
~~~
and
~~~
const average = function(a, b) {
return (a + b) / 2
}
~~~

A

Function declaration function product(a, b)
Function expression const average = function(a, b)
Function expressions in JavaScript are not hoisted, unlike function declarations. You can’t use function expressions before you create them

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

Stateful component
how to add state to the componen?

how should it change
what will happen when state is changed

A

useState
const [ counter, setCounter ] = useState(0)
The function returns an array that contains two items. We assign the items to the variables counter and setCounter by using the destructuring assignment syntax shown earlier.
When the state modifying function setCounter is called, React re-renders the component
it is forbidden in React to mutate state directly since it can result in unexpected side effects
must not be called from inside of a loop, a conditional expression, or any place that is not a function defining a component.

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

How to pass state to child components?

A

pass state and stateHandler in props to components
~~~
<Display counter={counter} />
<Button text={“Increase”} onClick={()=>setCount(++counter)} />
~~~

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

What is controlled component?

A

input element is controlled - it takes value from state hook and on change calls method to change this state

const [newNote, setNewNote] = useState('a new note...');

const handleNoteChange = (event) => {
 setNewNote(event.target.value)
}

<input
  value={newNote}
  onChange={handleNoteChange}
/>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to render a collection?
(to ul element for example)
[“HTML is easy”,”note 2”, “last note]

A
       <ul> {notes.map(note => 
        <li key={note.id}>
          {note.content} </li>
        )} </ul>
  

don’t us item index as uniqui id

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

JavaScript engines, or runtime environments, follow the asynchronous model.

What does it mean?

A

This requires all IO-operations (with some exceptions) to be executed as non-blocking. This means that code execution continues immediately after calling an IO function, without waiting for it to return.

When an asynchronous operation is completed, or, more specifically, at some point after its completion, the JavaScript engine calls the event handlers registered to the operation.

Currently, JavaScript engines are single-threaded As a result, it is a requirement in practice to use a non-blocking model for executing IO operations. Otherwise, the browser would “freeze” during, for instance, the fetching of data from a server.

In today’s browsers, it is possible to run parallelized code with the he
The event loop of an individual browser window is, however, still only handled by a single thread.

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

What is Promise

what states does it have

A

promise is an object that represents an asynchronous operation

A promise can have three distinct states:
- pending
- fulfilled
- rejected

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

What is Effect-hooks

at what point it is executed?

A

The Effect Hook lets you perform side effects on function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.
~~~
const hook = () => {
console.log(“effect”);
axios.get(‘http://localhost:3001/notes’)
.then((res) => {
console.log(‘responce recieced’)
setNotes(res.data);
})
}
useEffect(hook, []);
~~~
By default, effects run after every completed render, but you can choose to fire it only when certain values have changed.
The second parameter of useEffect is used to specify how often the effect is run. If the second parameter is an empty array [], then the effect is only run along with the first render of the component. (for example if passed, [sorce.props] - then it will be called only when this props will change);

The function passed to useEffect will run after the render is id done

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

How to pass handler to child with parameter in it
when ususally you pass just function name without a call ‘functionName’ rather than ‘functionName(variable)’

toggleIportanceOf(note.id)
A
<Note toggleImportance={()=>toggleImportanceOf(note.id)} />
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

We have array of notes[] - how to change one of notes field without mutating initial note in this array ( further this new object is send to server)

const newNote=…
const noteToEdit = …

A

~~~
const noteToEdit = notes.find(note => note.id == id);
const newNote = { …noteToEdit, important: !noteToEdit.important };
```

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

why needed
“proxy”: “http://localhost:3001”
in package.json

A

Since we are serving our react app from the same server where we have backend - we’ve changed url for the server on relative once
~~~
const baseUrl = ‘/api/notes’
~~~
so the local build won’t work without it

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

setUser(response.data);//valid user object
console.log(user)
what will be user here? //const {user, setUser} = useState({})

A

user will be undefined here - need to use response.data directly

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

how to change component visibility through inline styles?

A

<div style={{ display: isLoginFormVisible ? ‘’ : ‘none’ }}>

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

props.children when and how used?

A

Can be reused to make elements toggable
~~~
const Togglable = (props) => {
const [visible, setVisible] = useState(false)

const hideWhenVisible = { display: visible ? 'none' : '' }
const showWhenVisible = { display: visible ? '' : 'none' }

const toggleVisibility = () => {
    setVisible(!visible)
}

return (
    <div>
        <div style={hideWhenVisible}>
            <button onClick={toggleVisibility}>{props.buttonLabel}</button>
        </div>
        <div style={showWhenVisible}>
           {props.children}
            <button onClick={toggleVisibility}>cancel</button>
        </div>
    </div>
) } ~~~
19
Q

How to update object in array without modifying previous array

A

notesArray.map(n=>n.id===newNote.id?newNote:n);

20
Q

What is react?

A

JavaScript library for building user interfaces

it is not a framework

21
Q

design data first or ui first - what is the difference

A

like each component fetches and controls its data, or you have data and ui is attached to it

22
Q

How can be done showing/hiding elemts

A

Conditional rendering
and
inline style
~~~
<div style={{ display: (isLoginFormVisible || user) ? ‘’ : ‘none’ }}>
~~~

23
Q

How to make reusable wrapper for the component ( for example to make its visibility toggable)

A

Use props.children
~~~
<div style={showWhenVisible}>
{props.children}
<button onClick={toggleVisibility}>cancel</button>
</div>
~~~
children is automatically added by React and always exists. If a component is defined with an automatically closing /> tag - props.children is an empty array.

24
Q

Where to hold state

A

Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.
if App doesn’t need some states - it can be moved just to it component ( as was made in Toggable and Note (newNote,setNewNote)

25
Q

What is useRef and its 2 use cases

A

The useRef hook is used to reference components
~~~
const noteFormRef = useRef()

<Togglable buttonLabel='new note' ref={noteFormRef}>
  <NoteForm createNote={addNote} />
</Togglable> ~~~ ``` noteFormRef.current //will give us ToggableComponent ~~~ Then  to access its  function inside  the component we need to use  forwardRef and useImperativeHandle 

Another usecase - useRef holds the state between re-renderings, though it doesn’t force re-rendering when changed

const renderCounts = useRef(1)

useEffect(()=>{
renderCounts.current = 
renderCounts.current+1
})
//will increase each time component re-renders but wouldn't force re-rendering it self
26
Q

What is Cypress

A

It is library for e2e testin

27
Q

When to use Flux/Redux, what are the main components?

A

When applications grow larger, state management should be moved outside React components.
Store
Actions
Reducers
The state of the store is changed with actions.
The impact of the action to the state of the application is defined using a reducer.
In practice, a reducer is a function which is given the current state and an action as parameters. It returns a new state.
reducers must be pure functions - do not cause any side effects and they must always return the same response when called with the same parameters.

const counterReducer = (state, action) => {
  if (action.type === 'INCREMENT') {
    return state + 1
  } else if (action.type === 'DECREMENT') {
    return state - 1
  } else if (action.type === 'ZERO') {
    return 0
  }

  return state
}

subscribe is used to create callback functions the store calls whenever an action is dispatched to the store.

28
Q

What are action creators

A

Functions that create actions (for Redux architecture) are called action creators.
~~~
const toggleImportanceOf = (id) => {
return {
type: ‘TOGGLE_IMPORTANCE’,
data: { id }
}
~~~
```
store.dispatch(toggleImportanceOf(id))
~~~

29
Q

When to use react-redux together with redux

A

when a component is composed of many smaller components, there must be a way for all of the components to access the store.
~~~
<Provider store={store}>
<App></App>
</Provider>
~~~

import { useSelector, useDispatch } from 'react-redux'
 const notes = useSelector(state => state)
const dispatch = useDispatch()
	  dispatch(toggleImportanceOf(id))
30
Q

How to use several reducers?

A
const reducer = combineReducers({
  notes: noteReducer,
  filter: filterReducer,
})

then in selecotr we will refer to element we want
~~~
const notes = useSelector(state => state.notes)
~~~

31
Q

What is Redux Toolkit

A

The library for example greatly simplifies the configuration of the Redux store and offers a large variety of tools to ease state management.
With Redux Toolkit, we can easily create reducer and related action creators using the createSlice function
~~~
const noteSlice = createSlice({
name: ‘notes’,
initialState,
reducers: {
createNote(state, action) {
const content = action.payload
state.push({
content,
important: false,
id: generateId(),
})
}
})
~~~

The createSlice function’s name parameter defines the prefix which is used in the action’s type values. For example the createNote action defined later will have the type value of notes/createNote.
No need to wright actions separately

Actions will have same name as reducers
~~~
export const { createNote, toggleImportanceOf } = noteSlice.actions
export default noteSlice.reducer
~~~

32
Q

where you should not use hooks
why?

A

must not be called from inside of a loop
a conditional expression
or any place that is not a function defining a component.
This must be done to ensure that the hooks are always called in the same order, and if this isn’t the case the application will behave erratically.

33
Q

What is the difference between redux, react-redux, redux-toolkit

A

Adding redux gives an opportunity to create store, use reducers and actions
react-redux to share the redux-store with components - adds
~~~
const dispatch = useDispatch()
const notes = useSelector(state => state)
~~~
redux-toolkit simplifes work with redux - no need to write separate action creators all is described in silce
~~~
const noteSlice = createSlice({
name: ‘notes’,
initialState: [],
reducers: {
toggleImportanceOf(state, action) {
~~~

34
Q

What lib is used to communicate with server when using redux

A

redux-thunk allows implementations of asynchronous action creators, which first wait for the completion of a certain asynchronous operation and after that dispatch some action,
~~~
export const initializeNotes = () => {
return async dispatch => {
const notes = await noteService.getAll()
dispatch(setNotes(notes))
}
}
~~~

35
Q

Why to use reac router

A

can divide content by url adress in browser
browser back forward buttons work correctly

36
Q

Main components in router (navigate by code, navigate to single resource ,etc)

A

user right import
~~~
import {
BrowserRouter as Router,
} from “react-router-dom”
~~~
link to single resource
~~~
<Link to={/notes/${note.id}}>{note.content}</Link>
const note = match
? notes.find(note => note.id === Number(match.params.id))
: null
<Route path=”/notes/:id” element={<Note note={note} />} />
~~~
navigate from code
~~~
const navigate = useNavigate()
navigate(‘/’)
~~~

37
Q

Rules for using hooks

A

React hooks should be called in same order each render
- Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function.
- Don’t call Hooks from regular JavaScript functions. Instead, you can:
- Call Hooks from React function components.
- Call Hooks from custom Hooks

38
Q

What are custom hooks

A

The primary purpose of custom hooks is to facilitate the reuse of the logic used in components.
Building your own Hooks lets you extract component logic into reusable functions.
`const useCounter = () => {
const [value, setValue] = useState(0)

const increase = () => {
setValue(value + 1)
}

const decrease = () => {
setValue(value - 1)
}

const zero = () => {
setValue(0)
}

return {
value,
increase,
decrease,
zero
}
}`
and then use
~~~
const counter = useCounter()

return (
<div>
<div>{counter.value}</div>
<button onClick={counter.increase}>
plus
</button>
<button onClick={counter.decrease}>
minus
</button>
~~~

39
Q

What are custom hooks

A

The primary purpose of custom hooks is to facilitate the reuse of the logic used in components.
Building your own Hooks lets you extract component logic into reusable functions.
~~~
const useField = (type) => {
const [value, setValue] = useState(‘’)

const onChange = (event) => {
setValue(event.target.value)
}

return {
type,
value,
onChange
}
}
~~~
and then use
~~~
const App = () => {
const name = useField(‘text’)
// …

return (
<div>
<form>
<input
type={name.type}
value={name.value}
onChange={name.onChange}
/>
// …
</form>
</div>
)
}
~~~
even further - simplify it with spread operator
~~~
<input {…name} />
~~~
Custom hooks are clearly not only a tool for reuse, they also provide a better way for dividing our code into smaller modular parts.

40
Q

Name 3 main UI libraries for react

A

Bootstrap, materialUI, styled components

41
Q

What is the diffenece in state management betwenn class components and function components
what are other diffeneces?

A

the state of a Class component is a single object, and that the state is updated using the method setState, while in Functional components the state can consist of multiple different variables, with all of them having their own update function.

Class components use lifecircle methods instead of hooks
componentDidMount, componentWillUnmount

42
Q

what are the hooks to use in function component for componentDidMount, componentWillUnmount methods

A
    useEffect(() => {
        // Anything in here is fired on component mount.
        return () => {
            // Anything in here is fired on component unmount.
        }
    }, [])
43
Q

What is Virtual DOM

A

When a software developer uses React, they rarely or never directly manipulate the DOM. The function defining the React component returns a set of React elements. Although some of the elements look like normal HTML elements

const element = <h1>Hello, world</h1>

they are also just JavaScript-based React elements at their core.
With the help of the ReactDOM library, the virtual DOM defined by the components is rendered to a real DOM that can be shown by the browser using the DOM API

React has the previous version of the virtual DOM in memory and instead of directly rendering the new virtual DOM using the DOM API, React computes the optimal way to update the DOM (remove, add or modify elements in the DOM) such that the DOM reflects the new virtual DOM.

44
Q

Secutity in forntend backend?

A

Cross-site scripting (XSS) is an attack where it is possible to inject malicious JavaScript code into a legitimate web application. For example if we add note
~~~


alert('Evil XSS attack')

~~~
React takes care of sanitizing data in variables - so result will be simple string

The npm audit command can be used to check the security of dependencies. It compares the version numbers of the dependencies in your application to a list of the version numbers of dependencies containing known security threats in a centralized error database.
npm audit fix can fix some issues

for server
recommended to add a library called Helmet to the backend. It includes a set of middlewares that eliminate some security vulnerabilities in Express applications.