YouTip LogoYouTip

React Blog Usestate

Title: Responsive Data β€” useState | Online Tutorial\\\\n\\\\nuseState is React's most important Hook. In this chapter, you will understand React's state management mechanism and implement category filtering functionality.\\\\n\\\\n* * *\\\\n\\\\n## How is React's "Reactive" Different from Vue3?\\\\n\\\\nVue3 uses ref/reactive to create reactive data, and the view automatically updates when data changes.\\\\n\\\\nReact's approach is different: when you modify state, React re-executes the component function with the new state and renders a new view.\\\\n\\\\nThis is where React gets its name β€” components "react" to state changes.\\\\n\\\\n* * *\\\\n\\\\n## Basic useState Usage\\\\n\\\\nuseState is React's most basic Hook, used to add state to function components.\\\\n\\\\n## Example\\\\n\\\\n// From react destructure and import useState from\\\\n\\\\nimport{ useState } from 'react'\\\\n\\\\nfunction Counter(){\\\\n\\\\n// useState(initial value) returns an array:[Current value, Update function]\\\\n\\\\nconst[count, setCount]= useState(0)\\\\n\\\\nfunction handleClick(){\\\\n\\\\n setCount(count +1)// Update state, React will automatically re-render the component\\\\n\\\\n}\\\\n\\\\nreturn(\\\\n\\\\n
\\\\n\\\\n

Click count:{count}

\\\\n\\\\n\\\\n\\\\n
\\\\n\\\\n)\\\\n\\\\n}\\\\n\\\\nEvery time the button is clicked, `setCount` updates the count value, and React re-executes the Counter function with the new value, returning new JSX, and the page updates automatically.\\\\n\\\\n> React's convention: state is destructured as `[something, setSomething]`. The set prefix is a conventional naming pattern, not a strict requirement, but the entire community follows this convention.\\\\n\\\\n* * *\\\\n\\\\n## Why Can't We Directly Modify State?\\\\n\\\\nIn React, state is read-only. You must use the setter function to update it, not modify it directly.\\\\n\\\\n## Example\\\\n\\\\nimport{ useState } from 'react'\\\\n\\\\nfunction ArticleManager(){\\\\n\\\\nconst[title, setTitle]= useState('Default Title')\\\\n\\\\n// Wrong way: modify directly\\\\n\\\\n// title = 'New Title' // React Doesn't know you changed it, won't re-render\\\\n\\\\n// Correct way: update via setter\\\\n\\\\nfunction updateTitle(){\\\\n\\\\n setTitle('New Title')// React Knows state changed, will re-render\\\\n\\\\n}\\\\n\\\\nreturn(\\\\n\\\\n
\\\\n\\\\n

{title}

\\\\n\\\\n\\\\n\\\\n
\\\\n\\\\n)\\\\n\\\\n}\\\\n\\\\nThis follows React's Immutable principle: don't modify old data, but replace it with new data.\\\\n\\\\n* * *\\\\n\\\\n## The Correct Way to Update Arrays and Objects\\\\n\\\\nFor arrays and objects, you cannot directly push, splice, or modify properties β€” you must create new copies.\\\\n\\\\n## Example\\\\n\\\\nimport{ useState } from 'react'\\\\n\\\\nfunction TodoList(){\\\\n\\\\nconst[todos, setTodos]= useState([\\\\n\\\\n{ id:1, text:'Learn React', done:false},\\\\n\\\\n{ id:2, text:'Write Blog', done:true}\\\\n\\\\n])\\\\n\\\\n// Add an item: spread old array + new element\\\\n\\\\nfunction addTodo(text){\\\\n\\\\nconst newTodo ={ id:Date.now(), text, done:false}\\\\n\\\\n setTodos([...todos, newTodo])// Useuse the spread operator to create a new array\\\\n\\\\n}\\\\n\\\\n// Edit an item: map through, find the one to edit, return new object\\\\n\\\\nfunction toggleTodo(id){\\\\n\\\\n setTodos(todos.map(todo =>\\\\n\\\\n todo.id=== id ?{ ...todo, done:!todo.done}: todo\\\\n\\\\n))\\\\n\\\\n}\\\\n\\\\n// Delete an item: filter out the unwanted\\\\n\\\\nfunction removeTodo(id){\\\\n\\\\n setTodos(todos.filter(todo => todo.id!== id))\\\\n\\\\n}\\\\n\\\\nreturn(\\\\n\\\\n
    \\\\n\\\\n{todos.map(todo =>(\\\\n\\\\n
  • toggleTodo(todo.id)}>\\\\n\\\\n{todo.done?{todo.text}: todo.text}\\\\n\\\\n
  • \\\\n\\\\n))}\\\\n\\\\n
\\\\n\\\\n)\\\\n\\\\n}\\\\n\\\\n| Operation | Wrong Way | Correct Way |\\\\n| --- | --- | --- |\\\\n| Add | `arr.push(item)` | `setArr([...arr, item])` |\\\\n| Modify | `arr = newVal` | `setArr(arr.map(el => el.id === id ? ... : el))` |\\\\n| Delete | `arr.splice(i, 1)` | `setArr(arr.filter(el => el.id !== id))` |\\\\n| Modify Object Property | `obj.name = 'xxx'` | `setObj({ ...obj, name: 'xxx' })` |\\\\n\\\\n> Core principle: always replace the old array/object with a new one. The spread operator `...` and array methods you've learned (map, filter) are the best partners for immutable updates.\\\\n\\\\n* * *\\\\n\\\\n## useMemo β€” Derived Computed Values\\\\n\\\\nuseMemo is used to cache computation results. It skips recalculation when dependencies haven't changed, avoiding unnecessary performance overhead.\\\\n\\\\n## Example\\\\n\\\\nimport{ useState, useMemo } from 'react'\\\\n\\\\nfunction ArticleFilter(){\\\\n\\\\nconst= useState([\\\\n\\\\n{ id:1, title:'React Getting Started', category:'React'},\\\\n\\\\n{ id:2, title:'Promise Detailed Explanation', category:'JavaScript'},\\\\n\\\\n{ id:3, title:'Grid Layouts', category:'CSS'},\\\\n\\\\n{ id:4, title:'React Hooks', category:'React'}\\\\n\\\\n])\\\\n\\\\nconst[activeCategory, setActiveCategory]= useState('All')\\\\n\\\\n// useMemo Cache filtered results, only recalculate when dependencies change\\\\n\\\\nconst filteredArticles = useMemo(()=>{\\\\n\\\\n console.log('Recalculate filtered results')// Verify caching effect\\\\n\\\\nif(activeCategory ==='All')return articles\\\\n\\\\nreturn articles.filter(a => a.category=== activeCategory)\\\\n\\\\n},[articles, activeCategory])// Dependency array\\\\n\\\\n// Use useMemo calculate statistical data\\\\n\\\\nconst totalCount = useMemo(()=> articles.length,)\\\\n\\\\nconst filteredCount = useMemo(()=> filteredArticles.length,)\\\\n\\\\nreturn(\\\\n\\\\n
\\\\n\\\\n

Total {totalCount} posts,current {filteredCount} posts

\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n\\\\n{filteredArticles.map(a =>(\\\\n\\\\n

{a.title}

{a.category}
\\\\n\\\\n))}\\\\n\\\\n
\\\\n\\\\n)\\\\n\\\\n}\\\\n\\\\n> For useMemo(fn, deps), the dependency array must be complete: all component internal variables used in the function should be declared in the array. React uses shallow comparison to decide whether to recalculate.\\\\n\\\\n* * *\\\\n\\\\n## Hands-on: Add Category Filtering to the Blog\\\\n\\\\n## Example\\\\n\\\\n// File Path: src/App.jsx\\\\n\\\\nimport{ useState, useMemo } from 'react'\\\\n\\\\nimport'./App.css'\\\\n\\\\nfunction App(){\\\\n\\\\nconst= useState([\\\\n\\\\n{ id:1, title:'React Getting StartedComplete Guide', summary:'FromLearn React from Zero', category:'React
← React Blog RouterReact Blog Project Init β†’