# References for Using React
**Published by:** [coinvest](https://paragraph.com/@coinvest/)
**Published on:** 2023-09-19
**URL:** https://paragraph.com/@coinvest/references-for-using-react
## Content
A handy, quick reference for me (and everyone) to come back to when working with React. Sourced from: rstacruz / cheatsheets.Componentsimport React from 'react' import ReactDOM from 'react-dom' class Hello extends React.Component { render () { return
Hello {this.props.name}
} } const el = document.body ReactDOM.render(, el) Use the React.js jsfiddle to start hacking. (or the unofficial jsbin)Import multiple exportsimport React, {Component} from 'react' import ReactDOM from 'react-dom' class Hello extends Component { ... }Properties render () { this.props.fullscreen const { fullscreen, autoplay } = this.props ··· } Use this.props to access properties passed to the component. See: PropertiesStatesconstructor(props) { super(props) this.state = { username: undefined } } this.setState({ username: 'rstacruz' }) render () { this.state.username const { username } = this.state ··· } Use states (this.state) to manage dynamic data. With Babel you can use proposal-class-fields and get rid of constructor class Hello extends Component { state = { username: undefined }; ... } See: StatesNestingclass Info extends Component { render () { const { avatar, username } = this.props return
} } As of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM. import React, { Component, Fragment } from 'react' class Info extends Component { render () { const { avatar, username } = this.props return ( ) } } Nest components to separate concerns. See: Composing ComponentsChildren
You have pending notifications
class AlertBox extends Component { render () { return
{this.props.children}
} } Children are passed as the children property.DefaultsSetting default propsHello.defaultProps = { color: 'blue' } See: defaultPropsSetting default stateclass Hello extends Component { constructor (props) { super(props) this.state = { visible: true } } } Set the default state in the constructor(). And without constructor using Babel with proposal-class-fields. class Hello extends Component { state = { visible: true } } } See: Setting the default stateOther componentsFunctional componentsfunction MyComponent ({ name }) { return
Hello {name}
} Functional components have no state. Also, their props are passed as the first parameter to a function. See: Function and Class ComponentsPure componentsimport React, {PureComponent} from 'react' class MessageBox extends PureComponent { ··· } Performance-optimized version of React.Component. Doesn’t rerender if props/state hasn’t changed. See: Pure componentsComponent APIthis.forceUpdate() this.setState({ ... }) this.setState(state => { ... }) this.state this.props These methods and properties are available for Component instances. See: Component APILifecycleMountingMethodDescriptionconstructor *(props)*Before rendering #componentWillMount()Don’t use this #render()Render #componentDidMount()After rendering (DOM available) #------componentWillUnmount()Before DOM removal #------componentDidCatch()Catch errors (16+) # Set initial the state on constructor(). Add DOM event handlers, timers (etc) on componentDidMount(), then remove them on componentWillUnmount().UpdatingMethodDescriptioncomponentDidUpdate *(prevProps, prevState, snapshot)*Use setState() here, but remember to compare propsshouldComponentUpdate *(newProps, newState)*Skips render() if returns falserender()RendercomponentDidUpdate *(prevProps, prevState)*Operate on the DOM here Called when parents change properties and .setState(). These are not called for initial renders. See: Component specsHooks (New)State Hookimport React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return (
You clicked {count} times
); } Hooks are a new addition in React 16.8. See: Hooks at a GlanceDeclaring multiple state variablesfunction ExampleWithManyStates() { // Declare multiple state variables! const [age, setAge] = useState(42); const [fruit, setFruit] = useState('banana'); const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]); // ... }Effect hookimport React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); // Similar to componentDidMount and componentDidUpdate: useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${count} times`; }); return (
You clicked {count} times
); } If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. By default, React runs the effects after every render — including the first render.Building your own hooksDefine FriendStatusimport React, { useState, useEffect } from 'react'; function FriendStatus(props) { const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; } Effects may also optionally specify how to “clean up” after them by returning a function.Use FriendStatusfunction FriendStatus(props) { const isOnline = useFriendStatus(props.friend.id); if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; } See: Building Your Own HooksHooks API ReferenceAlso see: Hooks FAQBasic HooksHookDescriptionuseState(initialState)useEffect(() => { … })useContext*(MyContext)*value returned from React.createContext Full details: Basic HooksAdditional HooksHookDescriptionuseReducer(reducer, initialArg, init)useCallback(() => { … })useMemo(() => { … })useRef(initialValue)useImperativeHandle(ref, () => { … })useLayoutEffectidentical to useEffect, but it fires synchronously after all DOM mutationsuseDebugValue*(value)*display a label for custom hooks in React DevTools Full details: Additional HooksDOM nodesReferencesclass MyComponent extends Component { render () { return
this.input = el} />
} componentDidMount () { this.input.focus() } } Allows access to DOM nodes. See: Refs and the DOMDOM Eventsclass MyComponent extends Component { render () { this.onChange(event)} /> } onChange (event) { this.setState({ value: event.target.value }) } } Pass functions to attributes like onChange. See: EventsOther featuresTransferring props class VideoPlayer extends Component { render () { return } } Propagates src="..." down to the sub-component. See Transferring propsTop-level APIReact.createClass({ ... }) React.isValidElement(c) ReactDOM.render(, domnode, [callback]) ReactDOM.unmountComponentAtNode(domnode) ReactDOMServer.renderToString() ReactDOMServer.renderToStaticMarkup() There are more, but these are most common. See: React top-level APIJSX patternsStyle shorthandconst style = { height: 10 } return return See: Inline stylesInner HTMLfunction markdownify() { return "