State in React: Component State and Controlling Behavior

Author: neptune | 21st-Feb-2024
#JavaScript #React.js

React, a popular JavaScript library for building user interfaces, introduces the concept of state and lifecycle methods to help developers manage the dynamic nature of components. Understanding how to handle state and utilise lifecycle methods is crucial for creating responsive and interactive applications.

What is the State?

In React, the state is an object that represents the parts of a component that can change over time. State allows components to have dynamic behaviour and adapt to user interactions or other external factors. State is typically used to store data that may change during the lifecycle of a component.


Let's consider a simple example of a counter component:


    import React, { Component } from 'react';


    class Counter extends Component {

    constructor(props) {

        super(props);

        this.state = {

        count: 0

        };



Handling State in Functional Components with Hooks

With the introduction of React Hooks, functional components can also manage state using the `useState` hook. Let's rewrite the previous example using a functional component and the `useState` hook:


    import React, { useState } from 'react';


    const Counter = () => {

        const [count, setCount] = useState(0);


        return (

            <div>

                <p>Count: {count}</p>

                <button onClick={() => setCount(count + 1)}>

                    Increment

                </button>

            </div>

        );

    };



The `useState` hook simplifies state management in functional components by providing a way to declare state variables and their updater functions within the component function body.


Real-world Example: Timer Component

Let's explore a more practical example involving the lifecycle methods. Consider a timer component that displays the elapsed time since it was mounted.


    import React, { Component } from 'react';


    class Timer extends Component {

        constructor(props) {

            super(props);

            this.state = {

                secondsElapsed: 0

            };

        }


        componentDidMount() {

            this.interval = setInterval(() => {

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

            }, 1000);

        }


        componentWillUnmount() {

            clearInterval(this.interval);

        }


        render() {

            return (

                <div>

                    <p>Seconds Elapsed: {this.state.secondsElapsed}</p>

                </div>

            );

        }

    }


    export default Timer;



In this example, the `componentDidMount` method sets up an interval to update the component's state every second, simulating the passage of time. The `componentWillUnmount` method clears the interval to prevent memory leaks when the component is unmounted.


Wrapping Up

Understanding state and lifecycle methods in React is essential for building dynamic and responsive applications. By effectively managing state and utilising lifecycle methods, developers can create components that adapt to user interactions, update in real-time, and maintain optimal performance throughout their lifecycle. Whether using class components with lifecycle methods or functional components with hooks, React provides flexible and powerful tools for handling state and managing component behaviour.





Related Blogs
To Be Or Not To Be | #2704 | LeetCode Solution
Author: neptune | 03rd-Sep-2023
#JavaScript #LeetCode
Write a function that helps developers test their code. It should take in any value and return an object with the following two functions...

Create Your First App in React with Redux | Counter app
Author: neptune | 30th-Mar-2023
#React.js
Creating your first app in React can be a daunting task, but with the right guidance, it can be a fun and rewarding experience. Will guide you to create a counter app in React with redux...

React: Slideshow App | Fresco Play Hackerrank
Author: neptune | 05th-Nov-2023
#React.js
One interesting project that showcases these qualities is the Slideshow App, a simple yet impactful application that allows users to navigate through a collection of slides...

Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Author: neptune | 05th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element...

Counter | #2620 | LeetCode Solution
Author: neptune | 02nd-Sep-2023
#JavaScript #LeetCode
Given an integer n, return a counter function. This counter function returns n and then n + 1, n + 2, etc...

Function Composition | #2629 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions...

React.js vs React Native – What's the Difference?
Author: neptune | 26th-Mar-2023
#React.js
React.js and React Native are both frameworks developed by Facebook for building user interfaces. However, they are not the same and have different use cases...

Counter 2 | #2665 | LeetCode Solution
Author: neptune | 04th-Sep-2023
#JavaScript #LeetCode
Write function 'createCounter' It accept an initial integer 'init' It should return an object with three functions- increment() , decrement(), reset()...

Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Essential Topics to Master React JS
Author: neptune | 21st-Feb-2024
#React.js
A Comprehensive Guide to Components, State, JSX, Event Handling, Routing, Redux, Hooks, Testing, Performance Optimization, and Server-Side Rendering...

Array Reduce Transformation | #2626 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an integer array `nums` and a reducer function `fn`, and an initial value `init`, return a reduced array...

Add Two Promises | #2723 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
Given two promises `promise1` and `promise2`, return a new `promise`. `promise1` and `promise2` will both resolve with a number...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Filter Elements from Array | #2634 | LeetCode Solution
Author: neptune | 06th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a filtering function `fn`, return a filtered array `filteredArr`...

Is Object Empty | #2727 | LeetCode | JavaScript Solution
Author: neptune | 01st-Sep-2023
#JavaScript #LeetCode
Given an object or an array, return if it is empty...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

Opportunities - React Django Developer
Author: neptune | 14th-Apr-2023
#React.js #Django
React Django stack is popular for building web applications. Opportunities for React Django developers in Full Stack, Web, and Software development roles...

Chunk Array | #2677 | LeetCode Solution
Author: neptune | 19th-Sep-2023
#JavaScript #LeetCode
Given an array arr and a chunk `size`, return a `chunked` array...

Allow One Function Call | #2666 | LeetCode Solution
Author: neptune | 11th-Sep-2023
#JavaScript #LeetCode
Given a function `fn`, return a new function that is identical to the original function except that it ensures `fn` is called at most once...

Why React Refuses to Die ?
Author: neptune | 01st-Jun-2023
#React.js
React's success stems from addressing UI development challenges, nurturing a vibrant ecosystem, and its demand in the job market. Challenges exist, but React continues to evolve and remain relevant...

😱 How React Kicks Off OOPs ? 😱
Author: neptune | 01st-Jun-2023
#React.js
React kicks off OOPs by replacing inheritance with composition, achieving code reuse and modularity while promoting functional programming...

Memoize | #2634 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value...

Array Prototype Last | #2619 | LeetCode Solution
Author: neptune | 20th-Sep-2023
#JavaScript #LeetCode
Write code that enhances all arrays such that you can call the `array.last()` method on any array and it will return the last element...

All You Need to Know About Pure Functions & Impure Functions in JavaScript
Author: neptune | 02nd-Apr-2023
#JavaScript #React.js
You should try to use pure functions whenever possible and avoid using impure functions unless necessary...

Components and Props: Understanding the Backbone of React Applications
Author: neptune | 23rd-Jul-2023
#React.js
React is a popular JavaScript library for building user interfaces. One of the fundamental concepts in React is the use of components and props...

Functional vs Class Components in React: All you need to know?
Author: neptune | 21st-Apr-2023
#React.js
React components are building blocks for UIs. They can be functional (stateless) or class (stateful). Components are called using their names as HTML tags...

Celebrating 10 Years of React: A Decade of Innovation
Author: neptune | 01st-Jun-2023
#React.js
React celebrates its 10th anniversary, revolutionizing frontend development with its innovative concepts, ecosystem growth, and impact on mobile development...

A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
Author: neptune | 23rd-Feb-2024
#JavaScript
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers...

From REST to GraphQL: The Future of API Design
Author: neptune | 25th-Feb-2024
#JavaScript
Unlike traditional REST APIs, GraphQL provides a more flexible and intuitive approach to data querying and retrieval...

6 Brilliant JavaScript Frameworks for Every Developer
Author: neptune | 16th-Feb-2024
#JavaScript
JavaScript's web development with frameworks like Synaptic.js for neural networks, OpenCV.js for multimedia processing, D3.js for dynamic data visualizations, Compromise.js for efficient NLP, ConvNet...

Decode Secret Language of React: Game-Changer for Web Developers
Author: neptune | 25th-Feb-2024
#JavaScript #React.js
JSX is a syntax extension for JavaScript recommended by React for describing what the UI should look like...

View More