Mark Ku's Blog

The difference between state and props

In React, the main triggers for re-rendering are props and state.

1. props

Parameters passed in from outside the component. They are read-only and immutable — once created, they cannot be changed; you can only destroy and recreate to change the data. React decides whether an object has been modified by comparing memory references.

2. state

  • Private state belonging to a component, mainly used for passing data inside it. Apart from initialization in the constructor, modifications must go through setState, otherwise no re-render will happen (setState is asynchronous and doesn't update immediately).
  • Any state change in React that should trigger a render must call setState.
  • React's setState is asynchronous; the second-argument callback is the way to read the final value.
this.setState ({ count: this.state.count + 1 }, () => {
 console.log(this.state.count);
});
  • Calling setState twice with the same operation only runs once. You can pass a function to read the previous lifecycle's state (preState, preProps):
onClick={() => {
            this.setState(
              (preState, preProps) => {
                return { count: preState.count + 1 };
              }
            );

            this.setState(
              (preState, preProps) => {
                return { count: preState.count + 1 };
              }
            );
          }}

React components come in two flavors

React Class Component (the old style)

React component lifecycle diagram with mounting, updating, unmounting phases
React component lifecycle diagram with mounting, updating, unmounting phases

Lifecycle 1: Initialization

componentDidMount() — fires right after the component is mounted

Lifecycle 2: Update

Called when the component receives a new prop or after an update.

static getDerivedStateFromProps(props, state)

componentDidUpdate(prevProps, prevState)

P.S. Be careful: any setState call inside the component will re-trigger componentDidUpdate, so make sure your logic doesn't recurse infinitely.

shouldComponentUpdate — should the component update? Default true; return false to skip the update.

shouldComponentUpdate(nextProps, nextState) {
  return true; // 反回true 更新 false 不更新
}

Lifecycle 3: Destruction

componentWillUnmount() — called right before the component is destroyed; useful for avoiding memory leaks.

Function component (new projects' default App.tsx is also a function component now)

interface RobotProps {
  id: number;
  name: string;
  email: string;
}

interface RobotState {
  random:number
}

const Robot: React.FC<RobotProps,RobotState> = ({ id, name, email }) => {
const value = useContext(appContext)

  return (
          <div className={styles.cardContainer}>
            <img alt="robot" src={`https://robohash.org/${id}`} />
            <h2>{name}</h2>
            <p>{email}</p>
            <p>{value.username}</p>
          </div>
  );
};

export default Robot;

Two ways to get the correct this inside a function

1. bind this

onClick={this.handlerClick.bind(this)}>

2. arrow function — this will point to the React object itself

handlerClick = (e) => {
    this.setState({ isOpen: !this.state.isOpen });
};

Author

Mark Ku

擁有 10+ 年經驗的資深軟體工程師,現為 AI 應用 Builder,專注於大型平台架構與簡化複雜系統設計,從電商系統到訂閱與收費平台,結合 AI Agent、AI 整合與自動化開發,打造高效率且可持續演進的產品技術基礎。Read More

Found this useful?

The author's free tools, daily podcasts and newsletter are all here.

Mark Ku · This article is licensed under CC BY 4.0. Credit the author and link back to the original when reusing it.

Comments

Subscribe to Newsletter

Subscribe to get new posts delivered instantly — never miss a tech share.

By submitting, you agree to receive emails. You can anytime.

Popular Posts

View all
Mark Ku
··602

Oracle Cloud Always Free Tier: Linux Host and Static IP for a $0 Cloud Solution

Oracle Cloud Always Free Tier: Linux Host and Static IP for a $0 Cloud Solution
Mark Ku
··490

Say Goodbye to Postman's Fee Trap! A Hands-on Guide to Bruno, the Open-Source Git-Native API Testing Powerhouse.

Say Goodbye to Postman's Fee Trap! A Hands-on Guide to Bruno, the Open-Source Git-Native API Testing Powerhouse.
Mark Ku
··333

A Free, Open-Source, Notion-like Knowledge Base — A Complete Guide to Deploying and Backing Up Outline Wiki

A Free, Open-Source, Notion-like Knowledge Base — A Complete Guide to Deploying and Backing Up Outline Wiki
Mark Ku
··264

Training Your Own AI Voice: Hardware Requirements, Open-Source Model Comparison, and LoRA Fine-Tuning

Training Your Own AI Voice: Hardware Requirements, Open-Source Model Comparison, and LoRA Fine-Tuning
Mark Ku
··221

Building an Efficient API Management Platform: Deploying Kong Gateway from Scratch - Part 1

Building an Efficient API Management Platform: Deploying Kong Gateway from Scratch - Part 1
Mark Ku
··215

Setting Up Samba on Ubuntu to Share Folders with Windows 11

Setting Up Samba on Ubuntu to Share Folders with Windows 11