Quiz

How do you reset a component's state in React?

Topics
React
在GitHub上编辑

TL;DR

To reset a component's state in React, you can set the state back to its initial value. This can be done by defining an initial state and then using the setState function to reset it. For example, if you have a state object like this:

const [state, setState] = useState(initialState);

You can reset it by calling:

setState(initialState);

How do you reset a component's state in React?

Using functional components with hooks

In functional components, you can use the useState hook to manage state. To reset the state, you can simply call the setState function with the initial state value.

Example

import React, { useState } from 'react';
const MyComponent = () => {
const initialState = { count: 0, text: '' };
const [state, setState] = useState(initialState);
const resetState = () => {
setState(initialState);
};
return (
<div>
<p>Count: {state.count}</p>
<p>Text: {state.text}</p>
<button onClick={resetState}>Reset</button>
</div>
);
};
export default MyComponent;

Using class components

In class components, you can reset the state by calling this.setState with the initial state value.

Example

import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.initialState = { count: 0, text: '' };
this.state = this.initialState;
}
resetState = () => {
this.setState(this.initialState);
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<p>Text: {this.state.text}</p>
<button onClick={this.resetState}>Reset</button>
</div>
);
}
}
export default MyComponent;

Using a function to generate initial state

Sometimes, the initial state might be derived from props or other dynamic sources. In such cases, you can use a function to generate the initial state.

Example

import React, { useState } from 'react';
const MyComponent = (props) => {
const getInitialState = () => ({ count: props.initialCount, text: '' });
const [state, setState] = useState(getInitialState);
const resetState = () => {
setState(getInitialState());
};
return (
<div>
<p>Count: {state.count}</p>
<p>Text: {state.text}</p>
<button onClick={resetState}>Reset</button>
</div>
);
};
export default MyComponent;

Further reading

在GitHub上编辑