YouTip LogoYouTip

React State

Components can have state, which is the private part of a component's data and can be used to manage dynamic data.\n\nState only applies to class components, or can be used in function components when using React Hooks.\n\nReact treats components as State Machines. Through user interaction, different states are achieved, and then the UI is rendered to keep the user interface and data consistent.\n\nIn React, you only need to update the component's state, and then re-render the user interface based on the new state (do not manipulate the DOM).\n\nThe following example creates an ES6 class that extends React.Component, and uses this.state in the render() method to modify the current time.\n\nAdd a class constructor to initialize the state this.state. Class components should always call the base constructor with props.\n\n* * *\n\n### State Management in Class Components\n\nCreate a stateful class component:\n\n## Counter.js file\n\nimport React,{ Component } from 'react';\n\nclass Counter extends Component {\n\n constructor(props){\n\nsuper(props);\n\nthis.state={ count:0};\n\n}\n\nincrement =()=>{\n\nthis.setState({ count:this.state.count+1});\n\n}\n\nrender(){\n\nreturn(\n\n
\n\n

Count:{this.state.count}

\n\n\n\n
\n\n);\n\n}\n\n}\n\nexport default Counter;\n\nRender this component in src/index.js:\n\n## Instance\n\nimport React from 'react';\n\nimport ReactDOM from 'react-dom';\n\nimport'./index.css';\n\nimport Counter from './Counter';\n\nconst root = ReactDOM.createRoot(document.getElementById("root"));\n\n// Render the Counter component\n\n root.render();\n\n### State Management in Function Components (Using Hooks)\n\nUsing React Hooks allows you to use state in function components. The most commonly used Hook is useState.\n\nCreate a stateful function component:\n\n## Counter.js file\n\nimport React,{ useState } from 'react';\n\nfunction Counter(){\n\nconst[count, setCount]= useState(0);\n\nreturn(\n\n
\n\n

Count:{count}

\n\n\n\n
\n\n);\n\n}\n\nexport default Counter;\n\nRender this component in src/index.js:\n\n## Instance\n\nimport React from 'react';\n\nimport ReactDOM from 'react-dom';\n\nimport'./index.css';\n\nimport Counter from './Counter';\n\nconst root = ReactDOM.createRoot(document.getElementById("root"));\n\n// Render the Counter component\n\n root.render();\n\n* * *\n\n## Instance\n\nCreate a time instance to understand component state:\n\n## React Instance\n\nclass Clock extends React.Component{constructor(props){super(props); this.state = {date: new Date()}; }render(){return(

Hello, world!

It is now {this.state.date.toLocaleTimeString()}.

); }}const root = ReactDOM.createRoot(document.getElementById("root")); root.render();\n\n[Try it out Β»](#)\n\nNext, we will make the Clock set its own timer and update every second.\n\n### Adding Lifecycle Methods to a Class\n\nIn an application with many components, it is very important to release the resources occupied by components when they are destroyed.\n\nWhenever the Clock component is first loaded into the DOM, we want to generate a timer, which is called **mounting** in React.\n\nSimilarly, whenever the DOM generated by Clock is removed, we also want to clear the timer, which is called **unmounting** in React.\n\nWe can declare special methods on the component class to run some code when the component mounts or unmounts:\n\n## React Instance\n\nclass Clock extends React.Component{constructor(props){super(props); this.state = {date: new Date()}; }componentDidMount(){this.timerID = setInterval(() =>this.tick(), 1000); }componentWillUnmount(){clearInterval(this.timerID); }tick(){this.setState({date: new Date()}); }render(){return(

Hello, world!

It is now {this.state.date.toLocaleTimeString()}.

); }}const root = ReactDOM.createRoot(document.getElementById("root")); root.render();\n\n[Try it out Β»](#)\n\n**Instance Analysis:**\n\nThe componentDidMount() and componentWillUnmount() methods are called lifecycle hooks.\n\nAfter the component is output to the DOM, the componentDidMount() hook is executed, and we can set a timer on this hook.\n\nthis.timerID is the ID of the timer, and we can uninstall the timer in the componentWillUnmount() hook.\n\n**Code Execution Order:**\n\n1. When `` is passed to `ReactDOM.render()`, React calls the constructor of the `Clock` component. Since `Clock` needs to display the current time, `this.state` is initialized with an object containing the current time. We will update this state later.\n\n2. React then calls the `Clock` component's `render()` method. This is how React learns what should be displayed on the screen, and then React updates the DOM to match the `Clock`'s render output.\n\n3. When the `Clock`'s output is inserted into the DOM, React calls the `componentDidMount()` lifecycle hook. Inside it, the `Clock` component asks the browser to set up a timer to call `tick()` once a second.\n\n4. The browser calls the `tick()` method every second. Inside it, the `Clock` component schedules a UI update by calling `setState()` with an object containing the current time. By calling `setState()`, React knows the state has changed, and calls the `render()` method again to determine what should be displayed on the screen. This time, `this.state.date` in the `render()` method will be different, so the render output will contain the updated time, and the DOM will be updated accordingly.\n\n5. Once the `Clock` component is removed from the DOM, React calls the `componentWillUnmount()` hook function, and the timer will be cleared.\n\n### Data Flows Downwards\n\nNeither parent nor child components can know whether a certain component is stateful or stateless, and they should not care whether a component is defined as a function or a class.\n\nThis is why state is often called local or encapsulated. Other than the component that owns and sets it, no other components can access it.\n\nIn the following example, the FormattedDate component will receive the date value in its props, and it does not know whether it comes from the Clock's state, the Clock's props, or manual input:\n\n## React Instance\n\nfunction FormattedDate(props){return

It is now {props.date.toLocaleTimeString()}.

; }class Clock extends React.Component{constructor(props){super(props); this.state = {date: new Date()}; }componentDidMount(){this.timerID = setInterval(() =>this.tick(), 1000); }componentWillUnmount(){clearInterval(this.timerID); }tick(){this.setState({date: new Date()}); }render(){return(

Hello, world!

); }}const root = ReactDOM.createRoot(document.getElementById("root")); root.render();\n\n[Try it out Β»](#)\n\nThis is commonly referred to as a top-down or unidirectional data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components below it in the tree.\n\nIf you imagine a component tree as a waterfall of props, each component's state is like an additional water source that joins it at an arbitrary point, but also flows down.\n\nTo demonstrate that all components are truly isolated, we can create an App component that renders three Clocks:\n\n## React Instance\n\nfunction FormattedDate(props){return

It is now {props.date.toLocaleTimeString()}.

; }class Clock extends React.Component{constructor(props){super(props); this.state = {date: new Date()}; }componentDidMount(){this.timerID = setInterval(() =>this.tick(), 1000); }componentWillUnmount(){clearInterval(this.timerID); }tick(){this.setState({date: new Date()}); }render(){return(

Hello, world!

); }}function App(){return(
); }const root = ReactDOM.createRoot(document.getElementById("root")); root.render();\n\n[Try it out Β»](#)\n\nIn the above example, each Clock component sets up its own timer and updates independently.\n\nIn React applications, whether a component is stateful or stateless is considered an implementation detail of the component that may change over time.\n\nWe can use stateless components inside stateful components, or stateful components inside stateless components.
← C PointersReact Components β†’