search
HomeWeb Front-endJS TutorialKey Takeaways from My Recent Review of the React Docs

Key Takeaways from My Recent Review of the React Docs

This blog is originally posted on Medium

Hey there, fellow React enthusiasts! I've recently dived deep into the React documentation and want to share my learnings with you. This is a concise minimal guide for those who are looking to build a solid foundation in React. Let's break down the core concepts with simple explanations and code snippets.

This is going to be a somewhat lengthy story, but please hold on to grasp all the core concepts of React at once. You'll find it beneficial to recap and revisit these concepts for further advancement.

Table of Contents

  • Thinking in React
  • Components and JSX
  • Props
  • Conditional Rendering
  • Rendering Lists
  • Pure Components
  • UI Tree
  • Interactivity and Event Handlers
  • State
  • Controlled Components
  • Uncontrolled Components
  • Refs
  • Preventing Default Behavior
  • Event Propagation
  • Managing Complex States
  • Context
  • Side Effects
  • The best practices of useEffect
  • Rules of React
  • Custom Hooks
  • Rules of Hooks

Thinking in React

React is all about breaking your UI into reusable components. When building a React app, start by:

  1. Breaking the UI into a component hierarchy
  2. Building a static version with no interactivity
  3. Identifying the minimal representation of UI state
  4. Determining where your state should live
  5. Adding inverse data flow

Reference: https://react.dev/learn/thinking-in-react

Components and JSX

Components are the building blocks of React applications. They can be functional or class-based (old-fashioned, not recommended). JSX is a syntax extension that allows you to write HTML-like code in your JavaScript.

function Welcome(props) {
  return <h1 id="Hello-props-name">Hello, {props.name}</h1>;
}

References:

  • Components: https://react.dev/learn/your-first-component
  • JSX: https://react.dev/learn/writing-markup-with-jsx

Props

Props are how we pass data from parent to child components. They’re read-only and help keep our components pure.

function Greeting(props) {
  return <p>Welcome, {props.username}!</p>;
}

// Usage
<greeting username="Alice"></greeting>

Reference: https://react.dev/learn/passing-props-to-a-component

Conditional Rendering

React allows you to conditionally render components or elements based on certain conditions.

function UserGreeting(props) {
  return props.isLoggedIn ? <h1 id="Welcome-back">Welcome back!</h1> : <h1 id="Please-sign-in">Please sign in.</h1>;
}

Reference: https://react.dev/learn/conditional-rendering

Rendering Lists

Use the map() function to render lists of elements in React. Don't forget to add a unique key prop to each item.

function FruitList(props) {
  const fruits = props.fruits;

  return (
    
    {fruits.map((fruit) => (
  • {fruit.name}
  • ))}
); }

Reference: https://react.dev/learn/rendering-lists

Pure Components

Pure components always render the same output for the same props and state. They’re predictable and easier to test.

function Welcome(props) {
  return <h1 id="Hello-props-name">Hello, {props.name}</h1>;
}

Reference: https://react.dev/learn/keeping-components-pure

UI Tree

React builds and maintains an internal representation of your UI called the virtual DOM. This allows React to efficiently update only the parts of the actual DOM that have changed.

Reference: https://react.dev/learn/understanding-your-ui-as-a-tree

Interactivity and Event Handlers

React uses synthetic events to handle user interactions consistently across different browsers.

function Greeting(props) {
  return <p>Welcome, {props.username}!</p>;
}

// Usage
<greeting username="Alice"></greeting>

Reference: https://react.dev/learn/responding-to-events

State

State is used for data that changes over time in a component. Use the useState hook to add state to functional components.

function UserGreeting(props) {
  return props.isLoggedIn ? <h1 id="Welcome-back">Welcome back!</h1> : <h1 id="Please-sign-in">Please sign in.</h1>;
}

Reference: https://react.dev/learn/state-a-components-memory

Controlled Components

Controlled components have their state controlled by React.

function FruitList(props) {
  const fruits = props.fruits;

  return (
    
    {fruits.map((fruit) => (
  • {fruit.name}
  • ))}
); }

Uncontrolled Components

Uncontrolled components manage their state directly on the DOM.

function PureComponent(props) {
  return <div>{props.value}</div>;
}

Refs

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

function Button() {
  const handleClick = () => {
    alert('Button clicked!');
  };

  return <button onclick="{handleClick}">Click me</button>;
}

Preventing Default Behavior

Use preventDefault() to stop the default browser behavior for certain events.

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onclick="{()"> setCount(count + 1)}>Click me</button>
    </div>
  );
}

Event Propagation

React events propagate similarly to native DOM events. You can use stopPropagation() to prevent event bubbling.

function ControlledInput() {
  const [value, setValue] = useState('');
  return <input value="{value}" onchange="{e"> setValue(e.target.value)} />;
}

Managing Complex States

Consider using the useReducer hook or a state management library like Redux or Zustand for complex state logic.

function UncontrolledInput() {
  return <input defaultvalue="Hello">;
}

Context

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

import React, { useRef } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    inputEl.current.focus();
  };

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

Reference: https://react.dev/learn/passing-data-deeply-with-context

Side Effects

Side effects are operations that affect something outside the scope of the function being executed, like data fetching or DOM manipulation. Use the useEffect hook to manage side effects.

function Form() {
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Form submitted');
  };

  return 
...
; }

The best practices of useEffect

  1. Always include all variables on which your effect depends in the dependency array.
  2. Avoid infinite loops by carefully considering your effect’s dependencies.
  3. Clean up side effects in the return function of useEffect.
function Parent() {
  return (
    <div onclick="{()"> console.log('Parent clicked')}>
      <child></child>
    </div>
  );
}

function Child() {
  const handleClick = (e) => {
    e.stopPropagation();
    console.log('Child clicked');
  };

  return <button onclick="{handleClick}">Click me</button>;
}

References:

  • You Might Not Need useEffect: https://react.dev/learn/you-might-not-need-an-effect
  • Synchronizing with Effects: https://react.dev/learn/synchronizing-with-effects
  • Lifecycle of Reactive Effects: https://react.dev/learn/lifecycle-of-reactive-effects

Rules of React

  1. Always start component names with a capital letter.
  2. Close all tags, including self-closing tags.
  3. Don’t modify props directly.
  4. Keep components pure when possible.

Reference: https://react.dev/reference/rules

Custom Hooks

Custom hooks allow you to extract component logic into reusable functions.

function Welcome(props) {
  return <h1 id="Hello-props-name">Hello, {props.name}</h1>;
}

Rules of Hooks

  1. Only call hooks at the top level of your component.
  2. Only call hooks from React function components or custom hooks.
  3. Use eslint-plugin-react-hooks to enforce these rules.

Reference: https://react.dev/reference/rules/rules-of-hooks

That’s a wrap on our React journey! Remember, the best way to learn is by doing. Start building projects, experiment with these concepts, and don’t be afraid to dive into the React documentation when you need more details. Happy coding!

The above is the detailed content of Key Takeaways from My Recent Review of the React Docs. 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version