Home > Web Front-end > JS Tutorial > Advanced React Techniques Every Senior Developer Should Master

Advanced React Techniques Every Senior Developer Should Master

Barbara Streisand
Release: 2025-01-28 14:33:10
Original
292 people have browsed it

Advanced React Techniques Every Senior Developer Should Master

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.

  1. Higher-Order Components (HOCs): HOCs promote code reusability by taking a component and returning a modified version.
<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>
Copy after login
Copy after login
  1. Render Props: Share code between components using a prop whose value is a function.
<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>
Copy after login
Copy after login
  1. Context API: Facilitates data sharing across components, eliminating prop drilling.
<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>
Copy after login
Copy after login
  1. Custom Hooks: Encapsulate and reuse stateful logic.
<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>
Copy after login
  1. Error Boundaries: Catch and handle JavaScript errors within component trees.
<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>
Copy after login
  1. Code Splitting: Improve initial load times by splitting code into smaller chunks. (Webpack, Rollup, etc.)
<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>
Copy after login
  1. Memoization (useMemo): Optimize performance by caching expensive calculations.
<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>
Copy after login
  1. Portals: Render children into a different part of the DOM.
<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>
Copy after login
  1. Fragments: Group children without adding extra DOM nodes.
<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>
Copy after login
  1. Refs and the DOM: Access DOM nodes or React elements.
<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>
Copy after login
  1. Forwarding Refs: Pass refs through components to their children.
<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>
Copy after login
  1. Controlled and Uncontrolled Components: Manage component state either externally or internally.
<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>
Copy after login
  1. Performance Optimization (React.memo, useMemo, useCallback): Prevent unnecessary re-renders.
<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>
Copy after login
  1. Server-Side Rendering (SSR): Render components on the server for improved SEO and performance. (Requires a server-side framework like Next.js or Remix.)

  2. Static Site Generation (SSG): Pre-render pages at build time. (Next.js, Gatsby, etc.)

  3. Incremental Static Regeneration (ISR): Update static content after build time. (Next.js)

  4. 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>
Copy after login
Copy after login
  1. Suspense for Data Fetching: Declaratively handle loading states during data fetching.
<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>
Copy after login
Copy after login
  1. React Query: Simplify data fetching, caching, and synchronization.
<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>
Copy after login
Copy after login
  1. React Server Components: Combine client-side interactivity with server-side rendering benefits. (Requires a framework that supports RSC, like Next.js 13.)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template