Default Flashcards

1
Q

What are React Components?

A

Components in React have two jobs:

1) Return JSX, which tells react what we want to show on the screen to the user
2) Handle user events

All Components that we create in react are going to be functions that return JSX.

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

What is JSX?

A

JSX is a syntax extension to JavaScript. We can think of it as a set of instructions to tell react exactly what content we want to show on the screen at any given time.

JSX follows many similar rules to HTML. With JSX Elements we:

1) Tell React to create a normal HTML element
2) Tell react to show another component

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

What is the difference between React and ReactDOM?

A

When we work with React, we actually work with two different libraries - React and ReactDOM.

React - knows how get different components work together. How call a component function, how to get back JSX and how to iterate over JSX elements and decide whether to create some kind of html element or call other component function.
It’s referred as a ‘reconciler’

ReactDom - kwnows how to take instructions on what we want to show and turn it into HTML. Takes all the JSX, turns it into HTML and shows it to the user.
It’s called a ‘renderer’

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

What are the three tenets of React ecosystem

A

1) Component Nesting (a component can be shown inside of another
2) Component reusablility (we wnat to make components that can be easily reused through our application)
3) Component Configuration (we should be able to configure a component when it is created)

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

How do you nest components in our react App()

A
  1. We need to make the component available for import to outside files - we need to export the Component
const CommentDetail = () => {
  return <div> Some JSX </div>
}
export default CommentDetail
  1. We need to import the component using ES5 module system. And provide a relative path to the file

import CommentDetail from ‘./CommentDetail’

  1. In order to render it inside of our app, we need to nest it in the App, like so:
const App = () => {
  return (
    <div>
</div>   ); };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you work with React’s Props System?

A

Props system in react is a system for passing data from a parent component to a child component.
The goal of the system is to communicate data from parent to a child (customization and configuration of a child).

  1. You can provide props from parent to child by adding a property just as any other attribute, that we add in JSX.

This property is unique and passed only to that instance of the component that we are creating.

  1. In order to consume the information that we attach in the prop, we need to use it in the Component. By convention we add props variable as an argument of the component function.

And then refer to them with normal object properties
props.author

  1. We can also pass another components as props. In that case, they will be available under props.children
    We are not limited to just react components, we can pass plain text as well as just JSX
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the difference between Class Components and Function Components in React?

A

Class components:

  • use Lifesycle method system to run code at specific points of time.
  • Can use the ‘state’ system to update content on the screen

Functional Components (Stateless functional components)

  • Can use Hooks to run code at specific points in time.
  • Can use Hooks to access state system and update content on screen
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How can you setup a Class Component in React?

A

1) It must be a JavaScript Class
2) Must extend (subclass) React.Component
3) Must define a ‘render’ method that returns some amount of JSX

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

What are the rules of the State system in React?

A

1) Only usable with class components (technically can be used with functional components using ‘hooks’ system’)
2) ‘State’ is a JS object that contains data relevant to a component
3) Updating ‘state’ on a component will cause our component to almost instantly rerender.
4) State must be initialized when a component is created
5) State can only be updated using ‘setState’ function!

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

How can you initialize React’s state object and then update it using setState?

A

In React’s Class Component, we need to call the constructor method with argument super.

constructor(props){
  super(props);
// we need to initialize the state that we want to use, this is the only time we assign this.state directly
this.state = {lat: null}
}
// alternatively we can initialize the state by setting
class App extends React.Component {
  state = { lat: 40, errorMessage: '' };
}
which, when ran by babel will in turn compile it into a constructor function

// then we need to always use this.setState function

this.setState({lat: position.coords.latitude});

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

How can you set up conditional rendering in React’s Class Component?

A

In order to conditionally render content in React, one needs to set up if statements in the render() function and return JSX, like:
if (something){
return <div>Error: </div>
}

if (somethingElse){
return <div>Something else: </div>
}

return <div>Loading…</div>

We can also make use of ternary operators and short-circuit evaluation
{name=’Maciej’ ? ‘Witaj Macieju’ : ‘Witaj wędrowcze’}
{isError && <h1>Error…</h1>}

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

What methods does Component’s Lifecycle consist of?

A
| constructor (good place to do one-time setup)
| render (avoid doing anything besides returning JSX)
// content visible on the screen
| componentDidMount (Good place to do data-loading - the best practice, to load data is inside of this method instead of constructor function)
// Sit and wait for updates...
| componentDidUpdate (Good place to do more data-loading when state/props change)
// Sit and wait until this component is no longer shown
| componentWillUnmount (good place to do cleanup (especially for non-React stuff))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How can you apply Default Props to a Component?

A

In order to add default props to a component we need to assign them on the object
nameOfComponent.defaultProps = {}
like:

Spinner.defaultProps = {
message: ‘Loading’
};

It is advisable to setup defaultProps every time we want to create a very reusable component, so when we create it in different places of our app, we do not need to always pass a prop to display some content.

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

What are the benefits of Class based Components?

A

1) Can use ‘state’ (another React System) -> Easier to handle user input
2) Understands lifecycle events -> Easier to do things when the app first starts
3) Easier code organization

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

What is the difference between state and props in React?

A
  • “props” (short for “properties”) is an object of arbitrary inputs a React function component accepts as the first argument.
  • “state” is data that changes over the lifetime of a specific instance of a React component.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the naming convention that we should use when creating event handlers inside of our components?

A

onInputChange
So, we pass on, then the name of the element and then the event that triggers the element.
Another popular community convention is to assign name like: handleInputChange

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

Why making controlled elements in React World is so important?

A

If we do not set up the state of the element and store it in our React component, then HTML is the ONLY source of the data. Meaning, that if we want to get the value of let say an input, we need to each time reach into the input.value to see what’s there.

We are better off if we store the value on the state of the component

state = {term: ‘’}

  this.setState({ term: e.target.value })}/>
// go look at the state to get current value

Then, every time the component is rerendered (and it is rerendered every time we use setState function), the value of the input checks what’s the value of the state.term
Making React Component being the source of truth for the data -> and we have much more control over that.

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

How can you communicate events that happen on child elements to parents?

A

Whenever another component is nested into another one, we can pass a callback function as a prop on that component.

The class based child component, then in turn can after some event firing invoke that function from the child component -> It runs on the parent component

19
Q

How can you render a list of elements in react?

A

When we return JSX, we might as well return a mapped array of JSX elements. We are not limited only to <img></img> jsx tags.

return props.images.map((image) => {
return <img></img>;
});

However, probably, the best practice is to assign the result of the mapping function to a variable like images.

Then in the return (or render()) statement, wrap that list with a div tag - then, when we need to add additional styling/changes, the process will be much easier.

20
Q

What is the purpose of Keys in Lists and how can we implement them?

A

Most of the resources that we use to create list components contain some unique identification, that helps us identify the object.

React would like us to include this id as a key prop to each element that we are rendering. This key prop will be used when rerendering the app - this is how React looks up the differences between the rendered list and the one that’s currently sitting in the DOM.

This whole process is purely performance related.

21
Q

What is ref in React?

A

React Refs are a system to give you direct access to single dom element that is rendered by the component (we use it instead of document.querySelector function)

We create refs in the constructor, assign them to instance variables then pass a particular JSX element as props

constructor(props) {
super(props);

this.imageRef = React.createRef();   }

then in the render function

    return (
      <div>
        <img>
      </div>
    );

The <img></img> tag above, is not HTML -> it’s JSX, in order to have a reference to this element we need to use React’s Ref System.

22
Q

What is Hooks System in React?

A

Hooks System in React is about giving function components a lot of additional functionality. Normally, functional components cannot make use of state, lifecycle methods and refs.

Hooks system changes that with addition of functions:

useState - function that lets you use state in a functional component

useEffect - function that lets you use something lifecycle methods in a functional component

useRef - function that lets you create a ref in a function component

23
Q

What are React Fragments and what is their purpose?

A

A common pattern is for a component to return a list of children. In that case, we would need to wrap the returned list with a <div> or other element. In many cases, this might not produce valid html like:

<div>
  Hello
  World
</div>

The purpose of react fragments is to get rid off that issue.

You can declare react fragments either by wrapping the component with tags,
or the shorthand:

which looks like empty tags. You can use <» the same way you’d use any other element except that it doesn’t support keys or attributes.

key is the only attribute that can be passed to Fragment. In the future, we may add support for additional attributes, such as event handlers.</div>

24
Q

What is useState hook?

A

useState is a hook, that gives us access to state inside of a functional component.
1. Declare the state and setState() (sort of) function

const [activeIndex, setActiveIndex] = useState(null);

Whenever we use useState function, we get back an Array with two elements inside of it. We destructure it into

  • on position [0] - piece of state that we would like to track of
  • on position [1] - is a function that we call to update our piece of state. Just like with setState function - it will cause our entire component to rerender upon being called.

as useState arument we pass the INITIAL value.

25
Q

What is useEffect hook?

A
  • Allows function components to use something like lifecycle methods
  • We configure the hook to run some code automatically in one of three scenarios
    1) When the components is rendered for the first time only
    2) When the component is rendered for the first time and whenever it rerenders
    3) When the component is rendered for the first time and (whenever it rerenders and some piece of data has changed).

In the useEffect function, we will see as the first argument, the callback function
useEffect(() => {

}, secondArg)

and as the secondArg:
( 1) an empty array []),
( 2) no argument at all),
( 3) an array with some arguments inside [term, data])

26
Q

How does dangerouslySetInnerHTML work?

A

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:

function MyComponent() {
  return <div></div>
}
27
Q

How can you make use of useEffect’s Cleanup function?

A

The only thing that we can return from the callback function that is used together with useEffect, is a cleanup function.

  useEffect(() => {
    const search = async () => {
      // RUN async
    }
   return () => {
    // CLEANUP
   }
  }, [term]);

then, whenever it’s time to run useEffect function once again, first cleanup function will get invoked, then the useEffect function.

28
Q

What does useRef do?

A

useRef allows us to get a reference to a direct DOM element.

1) right after we declare piece of state:
const ref = useRef();
2) we are then going to assign ref object to one of the elements we are returning
3) to assign a ref we input ref={ref}
4) we can make use of that ref by accessing ref.current

  • it does not trigger re-render
  • targets DOM nodes/elements
29
Q

How can you change the url, without reloading the page

A

window.history.pushState({}, ‘’, href)

30
Q

What is the easiest, lowlevel way to set up navigation in react?

A

We should define Route and Link Components.
Route component, should display the children optionally depending on path prop.

Link Component should override <a> default behaviour with e.preventDefault() and</a>

run following piece of code, whenever somebody clicks on the link:

  const onClick = (e) => {
    if (e.metaKey || e.ctrlKey) return;
    e.preventDefault();
window.history.pushState({}, '', href);
    const navEvent = new PopStateEvent('popstate');
    window.dispatchEvent(navEvent);
  };

All of the routes should listen for popstate event and update current path based on the window.location.pathname

const Route = ({ path, children }) => {
  const [currentPath, setCurrentPath] = useState(window.location.pathname);
  useEffect(() => {
    const onLocationChange = () => {
      setCurrentPath(window.location.pathname);
    };
window.addEventListener('popstate', onLocationChange);   }, []);

return currentPath === path ? children : null;
};</a>

31
Q

How can you create Custom Hooks?

A
  • Custom hook are created by extracting hook-related code out of a function component.
  • Custom hooks always make use of at least one primitive hook internally
  • They will have one single purpose -> especially good when it comes to data fetching logic.

In order to create a reusable hook, we need to follow instructions:

1) Identify each line of code related to some single purpose
2) Identify the inputs
3) Identify the outputs
4) Extract all of the code into a seprarate function receiving the inputs as arugments and returning the outputs.

in the hook directory, we need to create a hook and pass it as an arguments a default value that we use when we initialize a hook, just like with useState hook. .

In the body of the fuciton we extract the logic of the hook,

the return values should follow React convention
return [videos, search]

32
Q

What is the function of React.forwardRef?

A

Ref forwarding is a technique for automatically passing a ref through a component to one of its children.

  1. We create a React ref by calling React.createRef and assign it to a ref variable.
  2. We pass our ref down to by specifying it as a JSX attribute.
  3. React passes the ref to the (props, ref) => … function inside forwardRef as a second argument.
  4. We forward this ref argument down to by specifying it as a JSX attribute.
  5. When the ref is attached, ref.current will point to the DOM node.
33
Q

What is the purpose of passing a function to setState function?

A

The reason is that State updates in React may be asynchronous

React may batch multiple setState() calls into a single update for performance.
Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

We can pass a function to setState, which will have access to the previous state, like:

  const complexIncrease = () => {
    setTimeout(() => {
      setValue((prevState) => prevState + 1);
    }, 2000);
  };
34
Q

What is useReducer hook used for?

A

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

const defaultState = {
  people: [],
  isModalOpen: false,
  modalContent: "Hello World",
}
const Index = () => {
  const [name, setName] = useState("");
  const [state, dispatch] = useReducer(reducer, defaultState);

return <div>Some JSX</div>
}

const reducer = (state, action) = {

}
// the reducer function depending on the action.type always has to return a new state object.
// we invoke it with calling dispatch method, that we got from initializing useReducer(reducer, initialState)
The dispatch method can contain information about a "type" of the method and payload, both of those properties are located on the action argument.
35
Q

How can we apply component composition in React app?

A

Some components don’t know their children ahead of time. This is especially common for components like Sidebar or Dialog that represent generic “boxes”.

We recommend that such components use the special children prop to pass children elements directly into their output

function FancyBorder(props) {
  return (
    <div>
      {props.children}
    </div>
  );
}
function WelcomeDialog() {
  return (
      <h1>
        Welcome
      </h1>
      <p>
        Thank you for visiting our spacecraft!
      </p>

);
}

Anything inside the JSX tag gets passed into the FancyBorder component as a children prop. Since FancyBorder renders {props.children} inside a <div>, the passed elements appear in the final output.</div>

36
Q

What is Context?

A

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

In order to use context API, we need to create context of our root component like:

const PersonContext = React.createContext();

we need to wrap the return of the root Component (App), with PersonContext.Provider and we can pass the values like: {//something}

With Context in the child elements, we no longer need to compose our components, or drill the props, we have access to the values by using useContext hook.

const {removePerson}= useContext(PersonContext);

37
Q

What does prop-types package do?

A

PropTypes is a library that helps in minimizing problem of trying to access properties on an object that is undefined in React by checking the types passed in the props object against a specification we set beforehand and to raise a warning if the types passed don’t match the types expected.

In order to set it up we need to:

import PropTypes from "prop-types";
// it is by default in create-react-app
Product.propTypes = {
  image: PropTypes.object.isRequired,
  name: PropTypes.string.isRequired,
  price: PropTypes.string.isRequired,
};
38
Q

What is the usecase of custom useGlobalContext hook?

A

In the Context API, we usually wrap the root element with an AppProvider component.

which returns
{children}

we can create a hustom hook called  useGlobalContext = () => {
return useContext(AppContext)
}

and import it wherever we need and destructure the functions/properties from the object.

const {showModal} = useGlobalContext()

39
Q

What is react router and what’s the basic setup?

A

React does not come by default with routing. React routing is an external library.

npm install react-router-dom

The basic setup for react router:

import { BrowserRouter as Router, Route, Switch } from “react-router-dom”;

We want to wrap our app with component.
Each of the routes pointing to different page Component.

40
Q

How do you display Error pages in React Router?

A

We need to setup a route for all of the other endpoints that do not point to some page.

However this setup would display the error page for every endpoint.

We need to wrap the Pages with a component.
With a component, only the first that matches is displayed

41
Q

How do you set up links in react router?

A

First, you need to import a component (instead of going for traditional link (anchor))

import { Link } from ‘react-router-dom’;

Home
has a specific prop, called, “to”, which onClick takes you this directory.

42
Q

How can you setup placeholder links/pages in react router? And why do we need them?

A

We use them, when we are iterating over a list and want to create a unique page for each of the list items.

In the Component - instead of passing the Component in the component, we add it as a prop children.

The path for the route also has url param, which in react router is refered by : and name of the param

}>

Then in the list, we set up a Component, the “to” prop should be set up dynamically:
Learn More

In order to access the :id param on the new page, we need to use useParams hook
import {Link, useParams} from ‘react-router-dom’

const {id} = useParams();

43
Q

What are HOC’s (Higher order components) and what are it’s usecases in React?

A

A higher-order component is a function that takes a component and returns a new component.