React JS Tutorial: Typing State 🎯

beginner
11 min

React JS Tutorial: Typing State 🎯

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.

What is State in React? 📝

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.

Why Use State? 💡

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.

Creating a State 🎯

Let's create a simple component with state.

jsx
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 vs Props 💡

State is specific to a component, while props are used for passing data from parent to child components.

Changing State 🎯

You can change state using setState() function. It accepts an object with new state properties to be merged with the current state.

jsx
this.setState({ count: this.state.count + 1 });

Functional Components and State 🎯

In functional components, you can use the useState hook to manage state.

jsx
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;

State and Conditional Rendering 🎯

You can use state to control the rendering of components based on certain conditions.

jsx
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;

Quiz 🎯

Quick Quiz
Question 1 of 1

What does state do in React?

Quick Quiz
Question 1 of 1

How do you change state in a functional component using the `useState` hook?