Welcome to our comprehensive guide on Typing State in React JS! This tutorial is designed to help beginners and intermediates understand the concept from the ground up.
In React, state is an object that stores dynamic data for a component. It allows components to be reactive and change based on user actions, form inputs, or any other dynamic data.
State is crucial because it allows components to update and re-render. Without state, a component would only render once and would not update with new data.
Let's create a simple component with state.
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
Count: {this.state.count}
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
export default Counter;In the above example, we create a Counter component that has a state of count: 0. When the Increment button is clicked, the state is updated, causing the component to re-render and display the new count.
State is specific to a component, while props are used for passing data from parent to child components.
You can change state using setState() function. It accepts an object with new state properties to be merged with the current state.
this.setState({ count: this.state.count + 1 });In functional components, you can use the useState hook to manage state.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
Count: {count}
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;You can use state to control the rendering of components based on certain conditions.
import React, { useState } from 'react';
function Greeting() {
const [name, setName] = useState('');
return (
<div>
{name ? <h1>Hello, {name}!</h1> : <h1>What's your name?</h1>}
<input type="text" onChange={e => setName(e.target.value)} />
</div>
);
}
export default Greeting;What does state do in React?
How do you change state in a functional component using the `useState` hook?