Flat Preloader Icon

Managing State

Managing state in React is crucial for creating dynamic and interactive user interfaces. React provides various ways to manage state, including using hooks in functional components and state management in class components.

Using ' useState ' in Functional Components

The useState hook is used to add state to functional components.
				
					import React, { useState } from 'react';

function Counter() {
  // Declare a state variable named 'count' with an initial value of 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}

export default Counter;

				
			
In this example, useState is used to declare a state variable ‘count’ and a function ‘setCount’ ‘to update it.

Using ' useReducer ' for More Complex State Logic

For more complex state logic, you can use the ‘useReducer’ hook.
				
					import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
}

export default Counter;

				
			
In this example, ‘useReducer’ is used to manage state with a reducer function and an initial state.

Managing State in Class Components

Before hooks, state was managed in class components using ‘this.state’ and ‘this.setState’.
				
					import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  decrement = () => {
    this.setState({ count: this.state.count - 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
        <button onClick={this.decrement}>Decrement</button>
      </div>
    );
  }
}

export default Counter;

				
			
In this example, ‘this.state’ is used to initialize the state, and ‘this.setState’ is used to update it.