React, a leading JavaScript library for crafting user interfaces (especially single-page applications), demands mastery of advanced techniques for building efficient, scalable, and maintainable projects. This article explores 20 essential advanced React concepts for senior developers, illustrated with TypeScript examples where relevant.
<code class="language-typescript">import React from 'react'; const withLogger = (WrappedComponent: React.ComponentType) => { return class extends React.Component { componentDidMount() { console.log(`Component ${WrappedComponent.name} mounted`); } render() { return <WrappedComponent {...this.props} />; } }; }; const MyComponent: React.FC = () => <div>Hello World</div>; const MyComponentWithLogger = withLogger(MyComponent);</code>
<code class="language-typescript">import React from 'react'; interface DataFetcherProps { render: (data: any) => JSX.Element; } const DataFetcher: React.FC<DataFetcherProps> = ({ render }) => { const data = { name: 'John Doe' }; return render(data); }; const MyComponent: React.FC = () => ( <DataFetcher render={(data) => <div>{data.name}</div>} /> );</code>
<code class="language-typescript">import React, { createContext, useContext } from 'react'; const MyContext = createContext<string | null>(null); const MyProvider: React.FC = ({ children }) => { const value = 'Hello from Context'; return <MyContext.Provider value={value}>{children}</MyContext.Provider>; }; const MyComponent: React.FC = () => { const value = useContext(MyContext); return <div>{value}</div>; };</code>
<code class="language-typescript">import { useState, useEffect } from 'react'; const useFetch = (url: string) => { const [data, setData] = useState<any | null>(null); useEffect(() => { fetch(url) .then((response) => response.json()) .then((data) => setData(data)); }, [url]); return data; }; const MyComponent: React.FC = () => { const data = useFetch('https://api.example.com/data'); return <div>{data ? data.name : 'Loading...'}</div>; };</code>
<code class="language-typescript">import React from 'react'; class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error: any) { return { hasError: true }; } componentDidCatch(error: any, errorInfo: any) { console.error(error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } const MyComponent: React.FC = () => { throw new Error('Test error'); return <div>Hello World</div>; }; const App: React.FC = () => ( <ErrorBoundary><MyComponent /></ErrorBoundary> );</code>
<code class="language-typescript">import React, { lazy, Suspense } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); const MyComponent: React.FC = () => ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> );</code>
<code class="language-typescript">import React, { useMemo } from 'react'; const MyComponent: React.FC = ({ items }) => { const sortedItems = useMemo(() => items.sort(), [items]); return <div>{sortedItems.join(', ')}</div>; };</code>
<code class="language-typescript">import React from 'react'; import ReactDOM from 'react-dom'; const MyPortal: React.FC = () => { return ReactDOM.createPortal( <div>This is rendered in a portal</div>, document.getElementById('portal-root')! ); };</code>
<code class="language-typescript">import React from 'react'; const MyComponent: React.FC = () => ( <React.Fragment> <div>Item 1</div> <div>Item 2</div> </React.Fragment> );</code>
<code class="language-typescript">import React, { useRef, useEffect } from 'react'; const MyComponent: React.FC = () => { const inputRef = useRef<HTMLInputElement>(null); useEffect(() => { inputRef.current?.focus(); }, []); return <input ref={inputRef} />; };</code>
<code class="language-typescript">import React, { forwardRef, useRef } from 'react'; const MyInput = forwardRef<HTMLInputElement>((props, ref) => ( <input {...props} ref={ref} /> )); const MyComponent: React.FC = () => { const inputRef = useRef<HTMLInputElement>(null); return <MyInput ref={inputRef} />; };</code>
<code class="language-typescript">import React, { useState, useRef } from 'react'; const ControlledComponent: React.FC = () => { const [value, setValue] = useState(''); return <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />; }; const UncontrolledComponent: React.FC = () => { const inputRef = useRef<HTMLInputElement>(null); return <input type="text" ref={inputRef} />; };</code>
<code class="language-typescript">import React, { useCallback, memo } from 'react'; const MyComponent: React.FC<{ onClick: () => void }> = memo(({ onClick }) => { console.log('Rendering MyComponent'); return <button onClick={onClick}>Click me</button>; }); const ParentComponent: React.FC = () => { const handleClick = useCallback(() => { console.log('Button clicked'); }, []); return <MyComponent onClick={handleClick} />; };</code>
Server-Side Rendering (SSR): Render components on the server for improved SEO and performance. (Requires a server-side framework like Next.js or Remix.)
Static Site Generation (SSG): Pre-render pages at build time. (Next.js, Gatsby, etc.)
Incremental Static Regeneration (ISR): Update static content after build time. (Next.js)
Concurrent Mode: Improve responsiveness and handle interruptions gracefully.
<code class="language-typescript">import React from 'react'; const withLogger = (WrappedComponent: React.ComponentType) => { return class extends React.Component { componentDidMount() { console.log(`Component ${WrappedComponent.name} mounted`); } render() { return <WrappedComponent {...this.props} />; } }; }; const MyComponent: React.FC = () => <div>Hello World</div>; const MyComponentWithLogger = withLogger(MyComponent);</code>
<code class="language-typescript">import React from 'react'; interface DataFetcherProps { render: (data: any) => JSX.Element; } const DataFetcher: React.FC<DataFetcherProps> = ({ render }) => { const data = { name: 'John Doe' }; return render(data); }; const MyComponent: React.FC = () => ( <DataFetcher render={(data) => <div>{data.name}</div>} /> );</code>
<code class="language-typescript">import React, { createContext, useContext } from 'react'; const MyContext = createContext<string | null>(null); const MyProvider: React.FC = ({ children }) => { const value = 'Hello from Context'; return <MyContext.Provider value={value}>{children}</MyContext.Provider>; }; const MyComponent: React.FC = () => { const value = useContext(MyContext); return <div>{value}</div>; };</code>
Conclusion: Mastering these advanced techniques empowers senior React developers to create high-performing, maintainable, and robust applications. By integrating these strategies into your workflow, you'll be equipped to handle complex projects and deliver exceptional user experiences.
The above is the detailed content of Advanced React Techniques Every Senior Developer Should Master. For more information, please follow other related articles on the PHP Chinese website!