React Basics Flashcards
What is React?
A JavaScript library for building user interfaces
What are 3 key characteristics?
- Declarative (describe what UI should look like, not implementation details)
- Component-based (reusable pieces of UI)
- Unidirectional data flow (data flows in 1 direction)
How do you add React to the DOM?
ReactDOM.render(<App></App>, document.getElementById(‘root’));
Implement useReducer
https://dev.to/craigaholliday/using-the-usereducer-hook-in-react-with-typescript-27m1
What are the stages / lifecycle of a component?
- Mount: initial render
- Update: re-render
- Unmount: removed from DOM
How do you hook into a component’s lifecycle?
useEffect(() => {}, [])
* used for performing side effects around the component lifecycle
* takes in a callback function
* will run after every render if no dependency array is given (an empty array will only render on mount)
* can also return a cleanup function which will run on unmount
* useEffect can be made to run synchronously (instead of asynchronously) using useLayoutEffect, meaning effects always finish running before the browser paints (but this has worst performance)
How can you reference the DOM node associated with a component?
The ref attribute
const element = useRef(null);
element.current = … <- how to define it
element.current; <- how to reference it
- Instances of ref will persist between renders
- Cannot reference ref until after initial render
- When passing ref to another component, use forwardRef
This is the same as:
const [element, setElement] = useState({ current: null });
element.current
// never use the setter, setElement, therefore component never re-renders (because object is immutable); changing value in an object isn’t going to cause re-render
const inputRef = useRef(null);
const focusInput = () => inputRef.current.focus();
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Click me</button>
<>
)
How can you share state between components?
Pull state up to the lowest common component and then drill props down to where needed
How can you use context to hold global state?
// ThemeContext.ts
import { createContext } from ‘react’;
export const ThemeContext = createContext({
theme: ‘light’,
})
// App.tsx
const [theme, setTheme] = useState({theme: ‘light’});
return (
<ThemeContext.Provider value={theme}>
<Page></Page>
</ThemeContext.Provider>
// Some component
import { useContext } from ‘react’;
import { ThemeContext } from ‘./ThemeContext’;
const { theme } = useContext(ThemeContext);
How to memoize an expensive function?
import { useMemo } from ‘react’;
const fibValue = useMemo(() => fib(num), [num]);
How to memoize an expensive component?
import { memo } from ‘react’;
const MyComponent = memo((props) => {
. . .
}, areEqual);
const areEqual = (prevProps, currProps) => prevProps === currProps;
// also need to pass memoized props (with useCallback for functions and useMemo for values)
// memo is used to memoize components while useMemo is used to memoize values
What is difference between useMemo and useCallback?
useMemo is for memoizing a value; useCallback is for memoizing a function
How can you lazy load a component that takes a long time to render?
import { lazy, Suspense } from ‘react’;
const MyComponent = lazy(() => import(‘./MyComponent’));
<Suspense fallback=(<div>Loading</div>)>
<MyButton>
</Suspense>
</MyButton>
What is a portal and how do you implement one?
A portal is a method for rendering React elements into a DOM node outside of the parent React tree. You need to add a second root element to index.html. The most common use cases are modals and tooltips.
import { createPortal } from ‘react-dom’;
const Modal = () => createPortal(<div>My portal</div>, document.getElementById(‘modal-root’));
How do you implement a class-based component?
import { Component, createRef } from ‘react’;
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: props.count ?? 0
}
this.buttonRef = createRef();
}
render() {
return <button ref={this.buttonRef} onClick={() => this.setState({ count: this.state.count + 1})>Increment</button>;
}
}
// Use methods to hook into lifecycle methods
// componentDidMount() { … }
// componentDidUpdate(prevProps, prevState) { … }
// componentWillUnmount() { … }
// shouldComponentUpdate(nextProps, nextState) { … }