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:
- Breaking the UI into a component hierarchy
- Building a static version with no interactivity
- Identifying the minimal representation of UI state
- Determining where your state should live
- 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
- Always include all variables on which your effect depends in the dependency array.
- Avoid infinite loops by carefully considering your effect’s dependencies.
- 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
- Always start component names with a capital letter.
- Close all tags, including self-closing tags.
- Don’t modify props directly.
- 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
- Only call hooks at the top level of your component.
- Only call hooks from React function components or custom hooks.
- 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!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor