>  기사  >  웹 프론트엔드  >  개발자를 위한 종합 React.js 치트시트

개발자를 위한 종합 React.js 치트시트

WBOY
WBOY원래의
2024-07-19 11:23:48419검색

Comprehensive React.js Cheatsheet for Developers

React.js는 동적 고성능 웹 애플리케이션 구축을 위한 현대 웹 개발의 초석이 되었습니다. 이 포괄적인 치트시트는 실제 예제, 코드 조각 및 모든 기능에 대한 자세한 설명을 포함하여 React.js를 마스터하기 위해 알아야 할 모든 것을 다루고 있습니다. 언제든지 참고할 수 있는 심층적인 가이드를 제공하는 것이 목표입니다.


1. 리액트 소개

React라고도 불리는 React.js는 특히 빠르고 대화형 사용자 경험이 필요한 단일 페이지 애플리케이션을 위한 사용자 인터페이스 구축에 사용되는 오픈 소스 JavaScript 라이브러리입니다. Facebook에서 개발한 React를 사용하면 개발자는 데이터 변경에 대응하여 효율적으로 업데이트하고 렌더링할 수 있는 대규모 웹 애플리케이션을 만들 수 있습니다.

React의 핵심 개념은 일부 출력을 렌더링하는 자체 포함 모듈인 구성 요소입니다. 구성 요소를 독립적으로 중첩, 관리 및 처리할 수 있으므로 개발 프로세스가 효율적이고 유지 관리 가능해집니다.

2. 리액트 시작하기

환경 설정

React를 시작하기 전에 개발 환경을 설정해야 합니다. 방법은 다음과 같습니다.

  1. Node.js 및 npm 설치: React는 종속성 관리를 위해 Node.js와 npm(노드 패키지 관리자)을 사용합니다.
  • 공식 홈페이지에서 Node.js를 다운로드하여 설치하세요.

  • 다음을 실행하여 설치를 확인하세요.

     node -v
     npm -v
    
  1. Create React App 설치: Create React App은 React를 배우기에 편안한 환경이자 React에서 새로운 단일 페이지 애플리케이션을 시작하는 좋은 방법입니다.

    npm install -g create-react-app
    

새로운 React 앱 만들기

환경이 설정되면 새로운 React 애플리케이션을 만들 수 있습니다.

  1. 새 프로젝트 만들기:

    npx create-react-app my-app
    cd my-app
    npm start
    

이 명령은 지정된 이름(my-app)으로 새 디렉터리를 생성하고 새 React 프로젝트를 설정한 후 개발 서버를 시작합니다. 브라우저를 열고 http://localhost:3000으로 이동하여 새로운 React 애플리케이션을 볼 수 있습니다.

3. 리액트 컴포넌트

구성요소는 모든 React 애플리케이션의 구성 요소입니다. UI를 독립적이고 재사용 가능한 부분으로 분할할 수 있습니다.

기능성 구성 요소

기능적 구성 요소는 props를 인수로 받아들이고 React 요소를 반환하는 JavaScript 함수입니다. 클래스 구성요소보다 더 간단하고 작성하기 쉽습니다.

import React from 'react';

const Welcome = ({ name }) => {
  return 4a249f0d628e2318394fd9b75b4636b1Welcome, {name}!473f0a7621bec819994bb5020d29372a;
};

export default Welcome;

클래스 구성요소

클래스 구성 요소는 React.Component를 확장하고 React 요소를 반환하는 렌더링 메서드를 갖는 ES6 클래스입니다.

import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return 4a249f0d628e2318394fd9b75b4636b1Welcome, {this.props.name}!473f0a7621bec819994bb5020d29372a;
  }
}

export default Welcome;

기능적 구성요소와 클래스 구성요소의 차이점

  • 상태 관리: 기능적 구성 요소는 상태 관리를 위해 후크(useState, useEffect 등)를 사용하는 반면, 클래스 구성 요소는 this.state 및 수명 주기 메서드를 사용합니다.

  • 수명 주기 메서드: 클래스 구성 요소에는 componentDidMount, componentDidUpdate 및 componentWillUnmount와 같은 수명 주기 메서드가 있습니다. 기능적 구성 요소는 useEffect 후크를 사용하여 부작용을 처리합니다.

  • 단순성: 기능적 구성 요소가 더 간단하고 장황하지 않아 읽고 유지하기가 더 쉽습니다.

4.JSX

JSX는 JavaScript 내에서 HTML을 직접 작성할 수 있는 구문 확장입니다. React "요소"를 생성합니다.

JSX 구문

JSX는 HTML처럼 보이지만 JavaScript로 변환됩니다.

const element = 4a249f0d628e2318394fd9b75b4636b1Hello, world!473f0a7621bec819994bb5020d29372a;

표현식 포함

중괄호로 묶어 JSX에 JavaScript 표현식을 삽입할 수 있습니다.

const name = 'John';
const element = 4a249f0d628e2318394fd9b75b4636b1Hello, {name}!473f0a7621bec819994bb5020d29372a;

JSX 속성

JSX를 사용하면 HTML과 유사한 구문으로 속성을 사용할 수 있습니다.

const element = 475c150c326c59ec9b2dd1e6a1c38014;

5. 주와 소품

상태 이해

State는 구성 요소에 속하는 속성 값을 저장하는 내장 개체입니다. 상태 객체가 변경되면 구성 요소가 다시 렌더링됩니다.

useState Hook을 사용하여 상태 관리

useState 후크는 기능적 구성요소에 상태를 추가하는 데 사용됩니다.

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      e388a4556c0f65e1904146cc1a846beeYou clicked {count} times94b3e26ee717c64999d7867364b1b4a3
      5ddc0978355752d4bf828563dc007a14 setCount(count + 1)}>Click me65281c5ac262bf6d81768915a4a77ac0
    16b28748ea4df4d9c2150843fecfba68
  );
};

export default Counter;

소품 이해

Prop은 React 구성 요소에 전달되는 인수입니다. Prop은 HTML 속성을 통해 구성 요소에 전달됩니다.

전달 소품

props는 읽기 전용이며 변경할 수 없습니다.

const Greeting = (props) => {
  return 4a249f0d628e2318394fd9b75b4636b1Hello, {props.name}!473f0a7621bec819994bb5020d29372a;
};

const App = () => {
  return 1e9b83e740a258dee7f01e880ba004db;
};

Prop 유형 및 기본 Prop

PropType을 사용하면 구성 요소가 수신해야 하는 prop 유형을 정의할 수 있습니다. 속성이 지정되지 않은 경우 속성이 값을 갖도록 기본 속성을 정의할 수 있습니다.

import React from 'react';
import PropTypes from 'prop-types';

const Greeting = ({ name }) => {
  return 4a249f0d628e2318394fd9b75b4636b1Hello, {name}!473f0a7621bec819994bb5020d29372a;
};

Greeting.propTypes = {
  name: PropTypes.string.isRequired,
};

Greeting.defaultProps = {
  name: 'Guest',
};

export default Greeting;

6. Component Lifecycle

Lifecycle Methods in Class Components

Lifecycle methods are special methods in class components that run at specific points in a component's life.

  • componentDidMount: Executed after the component is rendered.

  • componentDidUpdate: Executed after the component's updates are flushed to the DOM.

  • componentWillUnmount: Executed before the component is removed from the DOM.

class MyComponent extends React.Component {
  componentDidMount() {
    // Runs after component is mounted
  }

  componentDidUpdate(prevProps, prevState) {
    // Runs after component updates
  }

  componentWillUnmount() {
    // Runs before component is unmounted
  }

  render() {
    return dc6dce4a544fdca2df29d5ac0ea9906bMy Component16b28748ea4df4d9c2150843fecfba68;
  }
}

Using useEffect Hook

The useEffect hook combines the functionalities of componentDidMount, componentDidUpdate, and componentWillUnmount.

import React, { useState, useEffect } from 'react';

const MyComponent = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // Runs on mount and update
    document.title = `You clicked ${count} times`;

    // Cleanup function (runs on unmount)
    return () => {
      console.log('Cleanup');
    };
  }, [count]); // Dependency array

  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      e388a4556c0f65e1904146cc1a846beeYou

 clicked {count} times94b3e26ee717c64999d7867364b1b4a3
      5ddc0978355752d4bf828563dc007a14 setCount(count + 1)}>Click me65281c5ac262bf6d81768915a4a77ac0
    16b28748ea4df4d9c2150843fecfba68
  );
};

export default MyComponent;

7. Handling Events

Event Handling in React

React events are named using camelCase, rather than lowercase. With JSX, you pass a function as the event handler, rather than a string.

const handleClick = () => {
  console.log('Button clicked');
};

const MyComponent = () => {
  return a2cfc4f771b7cbacb8fc705e23ded36bClick me65281c5ac262bf6d81768915a4a77ac0;
};

Synthetic Events

React's event system is known as Synthetic Events. It is a cross-browser wrapper around the browser's native event system.

Handling Forms

Handling forms in React involves controlling the input elements and managing the state.

import React, { useState } from 'react';

const MyForm = () => {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + value);
  };

  return (
    a9bf9d9bedc9abd7dd4d836a79412b6a
      2e1cf0710519d5598b1f0f14c36ba674
        Name:
        504d17b0f6b03dc75f5b399918bed261
      8c1ecd4bb896b2264e0711597d40766c
      92e8cbd9feac6a729893ae422743759e
    f5a47148e367a6035fd7a2faa965022e
  );
};

export default MyForm;

Event Handler Best Practices

  • Avoid inline event handlers: Define event handlers outside of the JSX for better readability and performance.

  • Use Arrow Functions: Use arrow functions to avoid issues with this binding.

  • Debounce Expensive Operations: Debounce expensive operations like API calls to avoid performance issues.

8. Conditional Rendering

if-else Statements

You can use JavaScript if-else statements inside the render method.

const MyComponent = ({ isLoggedIn }) => {
  if (isLoggedIn) {
    return 4a249f0d628e2318394fd9b75b4636b1Welcome back!473f0a7621bec819994bb5020d29372a;
  } else {
    return 4a249f0d628e2318394fd9b75b4636b1Please sign in.473f0a7621bec819994bb5020d29372a;
  }
};

Ternary Operators

Ternary operators are a concise way to perform conditional rendering.

const MyComponent = ({ isLoggedIn }) => {
  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      {isLoggedIn ? 4a249f0d628e2318394fd9b75b4636b1Welcome back!473f0a7621bec819994bb5020d29372a : 4a249f0d628e2318394fd9b75b4636b1Please sign in.473f0a7621bec819994bb5020d29372a}
    16b28748ea4df4d9c2150843fecfba68
  );
};

Logical && Operator

You can use the logical && operator to include elements conditionally.

const MyComponent = ({ isLoggedIn }) => {
  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      {isLoggedIn && 4a249f0d628e2318394fd9b75b4636b1Welcome back!473f0a7621bec819994bb5020d29372a}
    16b28748ea4df4d9c2150843fecfba68
  );
};

Inline If with Logical && Operator

Inline if with logical && operator allows you to conditionally include an element in the output.

const Mailbox = ({ unreadMessages }) => {
  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      4a249f0d628e2318394fd9b75b4636b1Hello!473f0a7621bec819994bb5020d29372a
      {unreadMessages.length > 0 &&
        c1a436a314ed609750bd7c7d319db4da
          You have {unreadMessages.length} unread messages.
        2e9b454fa8428549ca2e64dfac4625cd
      }
    16b28748ea4df4d9c2150843fecfba68
  );
};

9. Lists and Keys

Rendering Lists

You can build collections of elements and include them in JSX using curly braces {}.

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  2e99a2afa389bfb220fcd51d65729993
    {number}
  bed06894275b65c1ab86501b08a632eb
);

const NumberList = () => {
  return (
    ff6d136ddc5fdfeffaf53ff6ee95f185{listItems}929d1f5ca49e04fdcb27f9465b944689
  );
};

Using Keys

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

const NumberList = (props) => {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    2e99a2afa389bfb220fcd51d65729993
      {number}
    bed06894275b65c1ab86501b08a632eb
  );
  return (
    ff6d136ddc5fdfeffaf53ff6ee95f185{listItems}929d1f5ca49e04fdcb27f9465b944689
  );
};

Keys Must Only Be Unique Among Siblings

Keys used within arrays should be unique among their siblings.

function Blog(props) {
  const sidebar = (
    ff6d136ddc5fdfeffaf53ff6ee95f185
      {props.posts.map((post) =>
        87c6bb9020f9bc84ce365f117dbefb25
          {post.title}
        bed06894275b65c1ab86501b08a632eb
      )}
    929d1f5ca49e04fdcb27f9465b944689
  );
  const content = props.posts.map((post) =>
    19bcd6b2eb431bc35ca7af1f5e43e263
      684271ed9684bde649abda8831d4d355{post.title}39528cedfa926ea0c01e69ef5b2ea9b0
      e388a4556c0f65e1904146cc1a846bee{post.content}94b3e26ee717c64999d7867364b1b4a3
    16b28748ea4df4d9c2150843fecfba68
  );
  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      {sidebar}
      231a563c997aa9e3e0ae614bd16728b0
      {content}
    16b28748ea4df4d9c2150843fecfba68
  );
}

10. Forms and Controlled Components

Handling Form Data

Handling form data in React involves managing the state of the form fields.

import React, { useState } from 'react';

const MyForm = () => {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + value);
  };

  return (
    a9bf9d9bedc9abd7dd4d836a79412b6a
      2e1cf0710519d5598b1f0f14c36ba674
        Name:
        504d17b0f6b03dc75f5b399918bed261
      8c1ecd4bb896b2264e0711597d40766c
      92e8cbd9feac6a729893ae422743759e
    f5a47148e367a6035fd7a2faa965022e
  );
};

export default MyForm;

Controlled vs Uncontrolled Components

Controlled components are those that are controlled by React state. Uncontrolled components are those that maintain their own internal state.

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      244054e4e8cabd44c7e8193aa6f63fb5
        2e1cf0710519d5598b1f0f14c36ba674
          Name:
          733698873fa50da8fa779e67406daca2
        8c1ecd4bb896b2264e0711597d40766c
        92e8cbd9feac6a729893ae422743759e
      f5a47148e367a6035fd7a2faa965022e
    );
  }
}

Using Refs for Uncontrolled Components

Refs provide a way to access DOM nodes or React elements created in the render method.

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.input = React.createRef();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      244054e4e8cabd44c7e8193aa6f63fb5
        2e1cf0710519d5598b1f0f14c36ba674
          Name:
          63001db5982f3e60a1b9208a578f6cf9
        8c1ecd4bb896b2264e0711597d40766c
        92e8cbd9feac6a729893ae422743759e
      f5a47148e367a6035fd7a2faa965022e
    );
  }
}

Form Validation

Form validation ensures that user inputs are valid.

const MyForm = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = (event) => {
    event.preventDefault();
    if (!name || !email) {
      setError('Name and Email are required');
    } else {
      setError('');
      // Submit form
    }
  };

  return (
    a9bf9d9bedc9abd7dd4d836a79412b6a
      {error && e388a4556c0f65e1904146cc1a846bee{error}94b3e26ee717c64999d7867364b1b4a3}
      2e1cf0710519d5598b1f0f14c36ba674
        Name:
        e6680c943276b2479743ae48aa2c3c4d setName(e.target.value)} />
      8c1ecd4bb896b2264e0711597d40766c
      2e1cf0710519d5598b1f0f14c36ba674
        Email:
        7448c870435c8466d6415b4cd5e57af3 setEmail(e.target.value)} />
      8c1ecd4bb896b2264e0711597d40766c
      92e8cbd9feac6a729893ae422743759e
    f5a47148e367a6035fd7a2faa965022e
  );
};

export default MyForm;

11. React Router

React Router is a library for routing in React applications. It allows you to handle navigation and rendering of different components based on the URL.

Setting Up React Router

  1. Install React Router:

    npm install react-router-dom
    
  2. Set Up Routes:

    import React from 'react';
    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
    
    const Home = () => <h2>Home</h2>;
    const About = () => <h2>About</h2>;
    
    const App = () => {
      return (
        <Router>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/about" component={About} />
          </Switch>
        </Router>
      );
    };
    
    export default App;
    

Route Parameters

You can use route parameters to capture values from the URL.

import React from 'react';
import { BrowserRouter as Router, Route,

 Switch, useParams } from 'react-router-dom';

const User = () => {
  const { id } = useParams();
  return c1a436a314ed609750bd7c7d319db4daUser ID: {id}2e9b454fa8428549ca2e64dfac4625cd;
};

const App = () => {
  return (
    a7f2cf15f06fbef780c6b2609731da81
      da7c15ee158c884a4ad5d56e941eda87
        ce6eeaea0ee015d7c7834a2da08622ed
      3fd1eab6a3ee1fe92fde6d97b1988f07
    80ecef3d33cd6309af735c93542122ea
  );
};

export default App;

Nested Routes

Nested routes allow you to render sub-components within a parent component.

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link, useRouteMatch } from 'react-router-dom';

const Topic = ({ match }) => 684271ed9684bde649abda8831d4d355Requested Topic ID: {match.params.topicId}39528cedfa926ea0c01e69ef5b2ea9b0;

const Topics = ({ match }) => {
  let { path, url } = useRouteMatch();
  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      c1a436a314ed609750bd7c7d319db4daTopics2e9b454fa8428549ca2e64dfac4625cd
      ff6d136ddc5fdfeffaf53ff6ee95f185
        25edfb22a4f469ecb59f1190150159c6
          b725e8e2701aa5ef3b10cf4a4a8d3034Components06f735b502bd5273dad825215f7c405b
        bed06894275b65c1ab86501b08a632eb
        25edfb22a4f469ecb59f1190150159c6
          8e1f596f8f79d213858f4f3ff1b58fceProps v. State06f735b502bd5273dad825215f7c405b
        bed06894275b65c1ab86501b08a632eb
      929d1f5ca49e04fdcb27f9465b944689
      da7c15ee158c884a4ad5d56e941eda87
        61f0fa4321c44137e30312030a9c0e20
          684271ed9684bde649abda8831d4d355Please select a topic.39528cedfa926ea0c01e69ef5b2ea9b0
        c14cb6b64e224f4e5a949337b2570e26
        9d194525d14decb3df37718d52f26590
      3fd1eab6a3ee1fe92fde6d97b1988f07
    16b28748ea4df4d9c2150843fecfba68
  );
};

const App = () => {
  return (
    a7f2cf15f06fbef780c6b2609731da81
      dc6dce4a544fdca2df29d5ac0ea9906b
        ff6d136ddc5fdfeffaf53ff6ee95f185
          25edfb22a4f469ecb59f1190150159c6
            4edbf5b784c612aafd5036a3e2d83c2dHome06f735b502bd5273dad825215f7c405b
          bed06894275b65c1ab86501b08a632eb
          25edfb22a4f469ecb59f1190150159c6
            b640d72ae84e3bad89e0179d1e328243Topics06f735b502bd5273dad825215f7c405b
          bed06894275b65c1ab86501b08a632eb
        929d1f5ca49e04fdcb27f9465b944689
        231a563c997aa9e3e0ae614bd16728b0
        da7c15ee158c884a4ad5d56e941eda87
          bbb3e500d9f4f89883020186a2ddbb4a
          f0e68096eeb3ed9fbd81056f58b8d5f3
        3fd1eab6a3ee1fe92fde6d97b1988f07
      16b28748ea4df4d9c2150843fecfba68
    80ecef3d33cd6309af735c93542122ea
  );
};

export default App;

Redirects and Navigation

You can use the Redirect component to redirect to a different route programmatically.

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';

const Home = () => c1a436a314ed609750bd7c7d319db4daHome2e9b454fa8428549ca2e64dfac4625cd;
const About = () => c1a436a314ed609750bd7c7d319db4daAbout2e9b454fa8428549ca2e64dfac4625cd;

const App = () => {
  return (
    a7f2cf15f06fbef780c6b2609731da81
      da7c15ee158c884a4ad5d56e941eda87
        bbb3e500d9f4f89883020186a2ddbb4a
        c9dc43901ba2d8c28c3c578e571107b7
        7709cf1d190ed88bc67892b77f43d992
      3fd1eab6a3ee1fe92fde6d97b1988f07
    80ecef3d33cd6309af735c93542122ea
  );
};

export default App;

12. Context API

The Context API provides a way to pass data through the component tree without having to pass props down manually at every level.

Creating Context

To create a context, use React.createContext.

const MyContext = React.createContext();

Consuming Context

To consume a context value, use the useContext hook in functional components or Context.Consumer in class components.

const MyComponent = () => {
  const value = useContext(MyContext);
  return dc6dce4a544fdca2df29d5ac0ea9906b{value}16b28748ea4df4d9c2150843fecfba68;
};

Context with Functional Components

const MyComponent = () => {
  return (
    b689c0d1a993785138e54bc7cc21f63f
      ea5c314853a1992950c8ee28be9bd72f
    8e66e6aff1f0a13ebced51b2c1b5d182
  );
};

const AnotherComponent = () => {
  const value = useContext(MyContext);
  return dc6dce4a544fdca2df29d5ac0ea9906b{value}16b28748ea4df4d9c2150843fecfba68;
};

Updating Context

To update context, create a provider component with state.

const MyProvider = ({ children }) => {
  const [value, setValue] = useState('Hello');
  return (
    682880ab8c111fd3ec21b55025046065
      {children}
    8e66e6aff1f0a13ebced51b2c1b5d182
  );
};

const MyComponent = () => {
  const { value, setValue } = useContext(MyContext);
  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      {value}
      5ddc0978355752d4bf828563dc007a14 setValue('Updated Value')}>Update65281c5ac262bf6d81768915a4a77ac0
    16b28748ea4df4d9c2150843fecfba68
  );
};

Context Best Practices

  • Avoid overusing context: Use context sparingly and only for global data.

  • Use multiple contexts: Separate concerns by using multiple contexts.

  • Memoize context values: Use useMemo to avoid unnecessary re-renders.

13. Hooks

Hooks are functions that let you use state and other React features in functional components.

Basic Hooks (useState, useEffect)

  • useState: Adds state to functional components.

  • useEffect: Performs side effects in functional components.

Additional Hooks (useContext, useReducer)

  • useContext: Accesses context values.

  • useReducer: Manages complex state logic.

const initialState = { count: 0 };

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, initialState);
  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      Count: {state.count}
      5ddc0978355752d4bf828563dc007a14 dispatch({ type: 'increment' })}>+65281c5ac262bf6d81768915a4a77ac0
      5ddc0978355752d4bf828563dc007a14 dispatch({ type: 'decrement' })}>-65281c5ac262bf6d81768915a4a77ac0
    16b28748ea4df4d9c2150843fecfba68
  );
}

Custom Hooks

Custom hooks are functions that encapsulate logic and can be reused across components.

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

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

  return data;
};

const MyComponent = () => {
  const data = useFetch('https://api.example.com/data');
  return dc6dce4a544fdca2df29d5ac0ea9906b{data ? JSON.stringify(data) : 'Loading...'}16b28748ea4df4d9c2150843fecfba68;
};

Rules of Hooks

  • Call hooks at the top level: Do not call hooks inside loops, conditions, or nested functions.

  • Only call hooks from React functions: Call hooks from functional components or custom hooks.

14. Higher-Order Components (HOC)

Higher-Order Components (HOC) are functions that take a component and return a new component.

Understanding HOCs

HOCs are used to add additional functionality to components.

const withLogging = (WrappedComponent) => {
  return (props) => {
    console.log('Rendering', WrappedComponent.name);
    return 31403eb0b6940459d9df68e14fc75564;
  };
};

Creating HOCs

const EnhancedComponent = withLogging(MyComponent);

Using HOCs

const MyComponent = (props) => {
  return dc6dce4a544fdca2df29d5ac0ea9906bMy Component16b28748ea4df4d9c2150843fecfba68;
};

const EnhancedComponent = withLogging(MyComponent);

HOC Best Practices

  • Do not mutate the original component: Return a new component.

  • Use display names for debugging: Set displayName on the HOC for better debugging.

15. 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.

Implementing Error Boundaries

Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

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

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

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    console.log(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return 4a249f0d628e2318394fd9b75b4636b1Something went wrong.473f0a7621bec819994bb5020d29372a;
    }

    return this.props.children; 
  }
}

Catching Errors

Error boundaries catch errors in the render method and in lifecycle methods.

const MyComponent = () => {
  throw new Error('An error occurred');
  return dc6dce4a544fdca2df29d5ac0ea9906bMy Component16b28748ea4df4d9c2150843fecfba68;
};

const App = () => {
  return (
    e61056d4a8a9030688e67f3b8b93a2b5
      c91df85aa2a01a1e069f702d655e9491
    cb28499deb11178577145cfc441388a7
  );
};

Error Boundaries Best Practices

  • Use error boundaries to catch errors in components: Use error boundaries to catch and display errors in UI components.

  • Log errors for debugging: Log errors to external services for debugging.

16. React Performance Optimization

Memoization

Memoization helps to avoid re-rendering components unnecessarily.

import React, { memo } from 'react';

const MyComponent = memo(({ value }) => {
  return dc6dce4a544fdca2df29d5ac0ea9906b{value}16b28748ea4df4d9c2150843fecfba68;
});

Code Splitting

Code splitting helps to load only the necessary code and improve performance.

import React, { Suspense, lazy } from 'react';

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

const MyComponent = () => {
  return (
    <Suspense fallback={dc6dce4a544fdca2df29d5ac0ea9906bLoading...16b28748ea4df4d9c2150843fecfba68}>
      8f13323f6387d4fb51abaf18b61b3667
    08ee156419279e45977839a62de7dfe8
  );
};

Lazy Loading

Lazy loading helps to load components only when they are needed.

import React, { Suspense, lazy } from 'react';

const Other

Component = lazy(() => import('./OtherComponent'));

const MyComponent = () => {
  return (
    <Suspense fallback={dc6dce4a544fdca2df29d5ac0ea9906bLoading...16b28748ea4df4d9c2150843fecfba68}>
      8f13323f6387d4fb51abaf18b61b3667
    08ee156419279e45977839a62de7dfe8
  );
};

useMemo and useCallback

  • useMemo: Memoizes expensive calculations.

  • useCallback: Memoizes functions.

const MyComponent = ({ value }) => {
  const memoizedValue = useMemo(() => {
    return computeExpensiveValue(value);
  }, [value]);

  const memoizedCallback = useCallback(() => {
    doSomething(value);
  }, [value]);

  return (
    dc6dce4a544fdca2df29d5ac0ea9906b
      {memoizedValue}
      f1e0750461fc4f521cd24a5533f81591Click me65281c5ac262bf6d81768915a4a77ac0
    16b28748ea4df4d9c2150843fecfba68
  );
};

React Developer Tools

Use React Developer Tools to identify performance bottlenecks.

17. Testing in React

Jest and React Testing Library

Jest and React Testing Library are popular tools for testing React components.

Writing Tests

  • Snapshot Testing: Capture the rendered component and compare it with a saved snapshot.

  • Unit Testing: Test individual components and functions.

  • Integration Testing: Test the integration between components and services.

import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

test('renders MyComponent', () => {
  render(c91df85aa2a01a1e069f702d655e9491);
  const element = screen.getByText(/My Component/i);
  expect(element).toBeInTheDocument();
});

18. React Best Practices

Component Structure

  • Organize components by feature: Group related components together.

  • Use descriptive names: Use clear and descriptive names for components and props.

  • Keep components small: Break down large components into smaller, reusable components.

State Management

  • Lift state up: Lift state to the nearest common ancestor.

  • 전역 상태에 Context 사용: 전역 상태 관리에 Context API를 사용합니다.

스타일링

  • CSS 모듈 사용: 범위 지정 및 모듈식 스타일에 CSS 모듈을 사용하세요.

  • 스타일 구성 요소 사용: 동적 스타일링을 위해 스타일 구성 요소를 사용하세요.

성능

  • 불필요한 재렌더링 방지: 메모 기능과 React에 내장된 성능 최적화 도구를 사용하세요.

  • 코드 분할 사용: 필요한 구성 요소만 로드하도록 코드를 분할합니다.

테스트

  • 포괄적인 테스트 작성: 애플리케이션의 모든 중요한 부분에 대한 테스트를 작성합니다.

  • 스냅샷 테스트 사용: 스냅샷 테스트를 사용하여 의도하지 않은 변경 사항을 포착합니다.

결론

React.js는 최신 웹 애플리케이션을 구축하기 위한 강력한 라이브러리입니다. 핵심 개념을 이해하고 활용함으로써 효율적이고 유지 관리 가능하며 확장 가능한 애플리케이션을 구축할 수 있습니다. 이 치트 시트는 기본 개념부터 고급 주제까지 모든 내용을 다루며 React.js를 마스터하는 데 도움이 되는 포괄적인 가이드 역할을 합니다.

위 내용은 개발자를 위한 종합 React.js 치트시트의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.