Featured image of post React Cheatsheet

React Cheatsheet

React Cheatsheet

ConceptSyntax/ExampleDescription
Componentclass MyComponent extends React.Component { ... }Class-based component
const MyComponent = () => { ... }Functional component
JSX<div>Hello, World!</div>JavaScript XML syntax
Props<MyComponent name="John" />Passing props to a component
Statethis.state = { count: 0 }; this.setState({ count: 1 });Component state in class-based components
const [count, setCount] = useState(0);State Hook in functional components
Lifecycle MethodscomponentDidMount() { ... }Lifecycle method in class-based components
useEffect(() => { ... }, []);Effect Hook in functional components
Event Handling<button onClick={this.handleClick}>Click me</button>Handling events in JSX
const handleClick = () => { ... };Event handler in functional components
Conditional Rendering{isLoggedIn ? <Dashboard /> : <Login />}Conditional rendering with JSX
Lists & Keys{items.map(item => <li key={item.id}>{item.name}</li>)}Rendering lists with unique keys
Forms<input type="text" value={this.state.value} onChange={this.handleChange} />Handling form input
const [value, setValue] = useState("");Handling form input with state in functional components
Refsthis.myRef = React.createRef();Creating a ref in class-based components
const myRef = useRef();Creating a ref in functional components
Contextconst MyContext = React.createContext();Creating a context
<MyContext.Provider value={value}>...</MyContext.Provider>Providing context value
const value = useContext(MyContext);Consuming context in functional components
Fragments<React.Fragment>...</React.Fragment>Using fragments to group elements
React Router<Router><Route path="/home" component={Home} /></Router>Setting up routing with React Router
Higher-Order Components (HOC)const withAuth = Component => props => { ... }Creating a HOC
Custom Hooksconst useCustomHook = () => { ... };Creating custom hooks
Suspense & Lazy Loadingconst LazyComponent = React.lazy(() => import('./LazyComponent'));Lazy loading components
Error BoundariescomponentDidCatch(error, info) { ... }Error handling in class-based components