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 = () => { returnHello, World!; };
JSX is a syntax extension that allows you to write HTML-like code within your JavaScript.
const MyComponent = () => { return (); };Welcome to React
Props are used to pass data from a parent component to a child component.
const Greeting = ({ name }) => { returnHello, {name}!
; }; // Usage
You can define default props for a component.
const Greeting = ({ name = "Guest" }) => { returnHello, {name}!
; };
The useState Hook allows you to add state to functional components.
import { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return (); };Count: {count}
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 returnData fetched. Check console.; };
Render different UI elements based on certain conditions.
const LoginMessage = ({ isLoggedIn }) => { return ({isLoggedIn ?); };Welcome back!
:Please log in.
}
Render lists of data and use keys to help React identify which items have changed.
const ItemList = ({ items }) => { return (
Handle events in functional components.
const Button = () => { const handleClick = () => { alert('Button clicked!'); }; return ; };
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 (); };
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 ({children} ); }; const MyComponent = () => { const contextValue = useContext(MyContext); return{contextValue}; };
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{data ? JSON.stringify(data) : 'Loading...'}; };
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{expensiveCalculation}; };
Use useCallback to memoize functions to prevent unnecessary re-renders.
import { useCallback } from 'react'; const Button = ({ onClick }) => { return ; }; const ParentComponent = () => { const handleClick = useCallback(() => { console.log('Button clicked'); }, []); return ; };
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 (); };Count: {state.count}
Use fragments to group multiple elements without adding extra nodes to the DOM.
const MyComponent = () => { return ( <>Title
Description
> ); };
Render children into a DOM node outside the parent component's DOM hierarchy.
import { createPortal } from 'react-dom'; const Modal = ({ children }) => { return createPortal({children}, 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) { returnSomething went wrong.
; } return this.props.children; } } // Usage
Dynamically import components to reduce the initial load time.
import { lazy, Suspense } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); const App = () => { return (Loading...
Use prop-types to document and enforce component prop types.
import PropTypes from 'prop-types'; const Greeting = ({ name }) => { returnHello, {name}!
; }; 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.
Atas ialah kandungan terperinci Lembaran Penipuan React: Edisi Komponen Fungsian. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!