React has evolved significantly since its inception, and with the rise of Hooks, functional components have become the go-to approach for building React applications. This cheat sheet provides an overview of the key concepts, features, and best practices for using functional components in React.
A functional component is a plain JavaScript function that returns a React element.
const MyComponent = () => { return <div>Hello, World!</div>; };
JSX is a syntax extension that allows you to write HTML-like code within your JavaScript.
const MyComponent = () => { return ( <div> <h1>Welcome to React</h1> </div> ); };
Props are used to pass data from a parent component to a child component.
const Greeting = ({ name }) => { return <h1>Hello, {name}!</h1>; }; // Usage <Greeting name="Alice" />
You can define default props for a component.
const Greeting = ({ name = "Guest" }) => { return <h1>Hello, {name}!</h1>; };
The useState Hook allows you to add state to functional components.
import { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); };
The useEffect Hook lets you perform side effects in functional components.
import { useEffect } from 'react'; const DataFetcher = () => { useEffect(() => { fetch('/api/data') .then(response => response.json()) .then(data => console.log(data)); }, []); // Empty dependency array means it runs once return <div>Data fetched. Check console.</div>; };
Render different UI elements based on certain conditions.
const LoginMessage = ({ isLoggedIn }) => { return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>} </div> ); };
Render lists of data and use keys to help React identify which items have changed.
const ItemList = ({ items }) => { return ( <ul> {items.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); };
Handle events in functional components.
const Button = () => { const handleClick = () => { alert('Button clicked!'); }; return <button onClick={handleClick}>Click Me</button>; };
Handle form input with controlled components.
const Form = () => { const [value, setValue] = useState(''); const handleChange = (e) => { setValue(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); alert(`Submitted value: ${value}`); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={value} onChange={handleChange} /> <button type="submit">Submit</button> </form> ); };
Use the Context API for state management across the component tree.
import { createContext, useContext } from 'react'; const MyContext = createContext(); const MyProvider = ({ children }) => { const value = 'Hello from context'; return ( <MyContext.Provider value={value}> {children} </MyContext.Provider> ); }; const MyComponent = () => { const contextValue = useContext(MyContext); return <div>{contextValue}</div>; };
Create reusable logic with custom hooks.
import { useState, useEffect } from 'react'; const useFetch = (url) => { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then(response => response.json()) .then(data => setData(data)); }, [url]); return data; }; // Usage const DataComponent = () => { const data = useFetch('/api/data'); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; };
Optimize performance by memoizing expensive calculations.
import { useMemo } from 'react'; const ExpensiveComponent = ({ number }) => { const expensiveCalculation = useMemo(() => { // Assume this is a computationally expensive operation return number * 2; }, [number]); return <div>{expensiveCalculation}</div>; };
Use useCallback to memoize functions to prevent unnecessary re-renders.
import { useCallback } from 'react'; const Button = ({ onClick }) => { return <button onClick={onClick}>Click me</button>; }; const ParentComponent = () => { const handleClick = useCallback(() => { console.log('Button clicked'); }, []); return <Button onClick={handleClick} />; };
Manage complex state logic with the useReducer Hook.
import { useReducer } from 'react'; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); } }; const Counter = () => { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); };
Use fragments to group multiple elements without adding extra nodes to the DOM.
const MyComponent = () => { return ( <> <h1>Title</h1> <p>Description</p> </> ); };
Render children into a DOM node outside the parent component's DOM hierarchy.
import { createPortal } from 'react-dom'; const Modal = ({ children }) => { return createPortal( <div className="modal"> {children} </div>, document.getElementById('modal-root') ); };
Use class components for error boundaries.
import { Component } from 'react'; class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.log(error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } // Usage <ErrorBoundary> <MyComponent /> </ErrorBoundary>
Dynamically import components to reduce the initial load time.
import { lazy, Suspense } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); const App = () => { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); };
Use prop-types to document and enforce component prop types.
import PropTypes from 'prop-types'; const Greeting = ({ name }) => { return <h1>Hello, {name}!</h1>; }; Greeting.propTypes = { name: PropTypes.string.isRequired, };
Functional components offer a clean and straightforward way to build React applications, especially with the powerful capabilities introduced by Hooks. This cheat sheet provides a quick reference to essential concepts, helping you write effective and efficient React code.
The above is the detailed content of React Cheat Sheet: Functional Components Edition. For more information, please follow other related articles on the PHP Chinese website!