Home > Web Front-end > JS Tutorial > body text

Essential React Tricks Every Developer Must Know

Mary-Kate Olsen
Release: 2024-11-03 12:58:02
Original
944 people have browsed it

React is incredibly powerful, but mastering it means going beyond the basics and learning some lesser-known tricks to streamline development. Here’s a rundown of my personal favourite 20 React tricks that can boost your productivity and help you write cleaner, more effective code. Let’s dive straight into examples!


1. Short-Circuit Evaluation for Conditional Rendering

Avoid verbose if statements for conditional rendering with short-circuit evaluation.

{isLoading && <Spinner />}
Copy after login
Copy after login

This renders the only when isLoading is true, keeping your JSX clean.


2. Dynamic Class Names with classnames Library

The classnames library makes it easy to conditionally apply classes.

npm install classnames
Copy after login
Copy after login
import classNames from 'classnames';

const buttonClass = classNames({
  'btn': true,
  'btn-primary': isPrimary,
  'btn-secondary': !isPrimary,
});

<button className={buttonClass}>Click Me</button>
Copy after login
Copy after login

3. Memoizing Expensive Calculations with useMemo

If a computation is costly, memoize it so React doesn’t recompute unnecessarily.

const sortedData = useMemo(() => data.sort(), [data]);
Copy after login
Copy after login

This recalculates sortedData only when data changes.


4. Debouncing Inputs with useEffect

Avoid constant re-renders by debouncing input changes.

const [value, setValue] = useState('');
const [debouncedValue, setDebouncedValue] = useState('');

useEffect(() => {
  const handler = setTimeout(() => setDebouncedValue(value), 500);
  return () => clearTimeout(handler);
}, [value]);

<input value={value} onChange={(e) => setValue(e.target.value)} />
Copy after login
Copy after login

5. Custom Hooks for Reusable Logic

Encapsulate logic in a custom hook to reuse it across components.

function useFetch(url) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url).then(res => res.json()).then(setData);
  }, [url]);

  return data;
}

const Component = () => {
  const data = useFetch('/api/data');
  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};
Copy after login
Copy after login

6. Lazy Loading Components with React.lazy

Optimize loading time by splitting your components.

const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
  return (
    <React.Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </React.Suspense>
  );
}
Copy after login
Copy after login

7. Accessing Previous Props or State with useRef

To access previous state values, use useRef.

const [count, setCount] = useState(0);
const prevCount = useRef(count);

useEffect(() => {
  prevCount.current = count;
}, [count]);

console.log(`Previous: ${prevCount.current}, Current: ${count}`);
Copy after login
Copy after login

8. Avoid Re-renders by Passing Functions to useCallback

If a function doesn’t need to change, memoize it with useCallback.

const increment = useCallback(() => setCount(count + 1), [count]);
Copy after login
Copy after login

9. Destructuring Props for Cleaner Code

Destructure props right in the function parameters.

const User = ({ name, age }) => (
  <div>{name} is {age} years old</div>
);
Copy after login
Copy after login

10. React.Fragment for Grouping Elements Without Extra Divs

Wrap elements without adding an extra DOM node.

<>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</>
Copy after login

11. Error Boundaries for Catching JavaScript Errors

Catch errors in child components to prevent the whole app from crashing.

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) return <h1>Something went wrong.</h1>;
    return this.props.children;
  }
}
Copy after login

Essential React Tricks Every Developer Must Know

Jagroop2001 (Jagroop) · GitHub

?‍? Full Stack Developer | ? Machine Learning Developer | ? Dev Relations Pro – ? Available for Hire - Jagroop2001

Essential React Tricks Every Developer Must Know github.com

12. Using PropTypes for Prop Validation

Catch bugs early by defining prop types.

{isLoading && <Spinner />}
Copy after login
Copy after login

13. State Reducers with useReducer

For complex state logic, useReducer can be more efficient.

npm install classnames
Copy after login
Copy after login

14. useLayoutEffect for DOM Manipulations

Run effects after DOM updates but before paint.

import classNames from 'classnames';

const buttonClass = classNames({
  'btn': true,
  'btn-primary': isPrimary,
  'btn-secondary': !isPrimary,
});

<button className={buttonClass}>Click Me</button>
Copy after login
Copy after login

15. Encapsulate State Logic with Context and useContext

Create global state without prop drilling.

const sortedData = useMemo(() => data.sort(), [data]);
Copy after login
Copy after login

16. Avoid Inline Function Definitions in JSX

Defining functions inline causes re-renders. Instead, define them outside.

const [value, setValue] = useState('');
const [debouncedValue, setDebouncedValue] = useState('');

useEffect(() => {
  const handler = setTimeout(() => setDebouncedValue(value), 500);
  return () => clearTimeout(handler);
}, [value]);

<input value={value} onChange={(e) => setValue(e.target.value)} />
Copy after login
Copy after login

17. Use Optional Chaining in JSX for Safe Property Access

Handle null or undefined values gracefully.

function useFetch(url) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url).then(res => res.json()).then(setData);
  }, [url]);

  return data;
}

const Component = () => {
  const data = useFetch('/api/data');
  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};
Copy after login
Copy after login

18. Use the key Prop to Avoid Re-rendering Issues

Always use unique keys when rendering lists.

const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
  return (
    <React.Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </React.Suspense>
  );
}
Copy after login
Copy after login

19. Export Components with Named Exports for Better Import Control

Named exports make importing specific components easier.

const [count, setCount] = useState(0);
const prevCount = useRef(count);

useEffect(() => {
  prevCount.current = count;
}, [count]);

console.log(`Previous: ${prevCount.current}, Current: ${count}`);
Copy after login
Copy after login

Then import as needed:

const increment = useCallback(() => setCount(count + 1), [count]);
Copy after login
Copy after login

20. Reusable Component Patterns: Higher-Order Components (HOCs)

Wrap components with HOCs to add extra logic.

const User = ({ name, age }) => (
  <div>{name} is {age} years old</div>
);
Copy after login
Copy after login

Mastering these tricks will help you write more concise, readable, and efficient React code! Happy coding!

The above is the detailed content of Essential React Tricks Every Developer Must Know. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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