Home >Web Front-end >JS Tutorial >React Basics Part 2

React Basics Part 2

DDD
DDDOriginal
2024-09-19 06:27:06803browse

React Basics Part 2

Here are some more advanced React concepts and terminologies:

12. Context API

The Context API provides a way to pass data through the component tree without having to pass props manually at every level. It is useful for global data like themes, authentication, or user data.

Example:

const ThemeContext = React.createContext('light');

function ThemedButton() {
  return (
    <ThemeContext.Consumer>
      {theme => <button className={theme}>I am styled by {theme} theme!</button>}
    </ThemeContext.Consumer>
  );
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedButton />
    </ThemeContext.Provider>
  );
}

13. Refs

Refs provide a way to access DOM nodes or React elements created in the render method. It’s often used to directly modify a DOM element or manage focus.

Example:

import { useRef } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);

  const onButtonClick = () => {
    inputEl.current.focus();
  };

  return (
    <div>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </div>
  );
}

14. Higher-Order Component (HOC)

An HOC is a function that takes a component and returns a new component. It’s often used to reuse component logic.

Example:

function withLogger(WrappedComponent) {
  return function WithLogger(props) {
    console.log('Rendering component');
    return <WrappedComponent {...props} />;
  };
}

const EnhancedComponent = withLogger(MyComponent);

15. React.memo

React.memo is a higher-order component that helps to optimize performance by memoizing a component. If the props haven't changed, the component will skip re-rendering.

Example:

const MyComponent = React.memo(function MyComponent(props) {
  return <div>{props.text}</div>;
});

16. useReducer Hook

The useReducer hook is an alternative to useState. It’s useful for managing more complex state logic, especially when the state depends on previous values.

Example:

import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <span>{state.count}</span>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
    </div>
  );
}

17. React Fragments

React Fragments let you group a list of children without adding extra nodes to the DOM.

Example:

function Table() {
  return (
    <>
      <tr>
        <td>Row 1</td>
      </tr>
      <tr>
        <td>Row 2</td>
      </tr>
    </>
  );
}

18. Portals

Portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component.

Example:

import ReactDOM from 'react-dom';

function Modal({ children }) {
  return ReactDOM.createPortal(
    <div className="modal">{children}</div>,
    document.getElementById('modal-root')
  );
}

19. Error Boundaries

Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI.

Example:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

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

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

20. Lazy Loading

React supports lazy loading of components, which means components can be loaded asynchronously when they are required, improving performance for large applications.

Example:

import React, { Suspense } from 'react';

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

function MyComponent() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <OtherComponent />
    </Suspense>
  );
}

21. StrictMode

StrictMode is a tool for highlighting potential problems in an application. It doesn’t render any visible UI but checks for issues like deprecated lifecycle methods.

Example:

function App() {
  return (
    <React.StrictMode>
      <MyComponent />
    </React.StrictMode>
  );
}

22. Controlled vs Uncontrolled Components

Controlled Components: Form elements where the value is controlled by React state.

Uncontrolled Components: Form elements where the value is handled by the DOM.

Example of Controlled Component:

function ControlledInput() {
  const [value, setValue] = useState('');

  return (
    <input
      type="text"
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />
  );
}

Example of Uncontrolled Component:

function UncontrolledInput() {
  const inputRef = useRef(null);

  return <input type="text" ref={inputRef} />;
}

23. Prop Drilling

Prop Drilling occurs when data is passed down through multiple levels of components to reach a deeply nested child. This can be avoided by using Context API or state management libraries.

Example of Prop Drilling:

function Grandparent() {
  const name = "John";
  return <Parent name={name} />;
}

function Parent({ name }) {
  return <Child name={name} />;
}

function Child({ name }) {
  return <p>{name}</p>;
}

24. Rendering Lifecycle

React components have a lifecycle with methods that are invoked at different stages, such as mounting, updating, and unmounting.

Lifecycle methods (class components):

  1. - componentDidMount
  2. - componentDidUpdate
  3. - componentWillUnmount

Example:

class MyComponent extends React.Component {
  componentDidMount() {
    console.log('Component mounted');
  }

  componentDidUpdate() {
    console.log('Component updated');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  render() {
    return <div>Hello!</div>;
  }
}

25. useRef Hook

The useRef hook is used to persist values across renders without causing a re-render. It’s commonly used for accessing DOM elements or storing mutable values.

Example:

function Timer() {
  const countRef = useRef(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      countRef.current += 1;
      console.log(countRef.current);
    }, 1000);

    return () => clearInterval(intervalId);
  }, []);

  return <p>Check the console to see the timer.</p>;
}

These additional concepts will help you deepen your understanding of React and tackle more advanced scenarios!

The above is the detailed content of React Basics Part 2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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