What is State Management in React JS?

#local state

#state management

State management in React refers to the practice of handling the state of your application to ensure that your UI consistently reflects the current data and state of your application. State management becomes crucial as your application grows in complexity, and managing `state` across multiple components can become challenging. React provides various ways to manage state, including built-in tools and third-party libraries.

Local State

Local state refers to the state that is managed within a single component. This is typically handled using React's useState hook in functional components or the `this.state` and this.setState methods in class components.

Example: Local State with `useState`

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;

Lifting State Up

When multiple components need to share state, you can lift the state up to their closest common ancestor. This allows the ancestor to manage the state and pass it down to child components as props.

Example: Lifting State Up

import React, { useState } from 'react';

function TemperatureInput({ temperature, onTemperatureChange }) {
  return (
    <fieldset>
      <legend>Enter temperature in Celsius:</legend>
      <input value={temperature} onChange={e => onTemperatureChange(e.target.value)} />
    </fieldset>
  );
}

function Calculator() {
  const [temperature, setTemperature] = useState('');

  return (
    <div>
      <TemperatureInput
        temperature={temperature}
        onTemperatureChange={setTemperature}
      />
      <BoilingVerdict celsius={parseFloat(temperature)} />
    </div>
  );
}

function BoilingVerdict({ celsius }) {
  if (celsius >= 100) {
    return <p>The water would boil.</p>;
  }
  return <p>The water would not boil.</p>;
}

export default Calculator;

Context API

The Context API is used to manage global state. It allows you to create context objects that can be accessed by any component within the context provider.

Example: Context API

import React, { createContext, useState, useContext } from 'react';

// Create a context
const ThemeContext = createContext();

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

function ThemeButton() {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Toggle Theme
    </button>
  );
}

function App() {
  return (
    <ThemeProvider>
      <div>
        <ThemeButton />
      </div>
    </ThemeProvider>
  );
}

export default App;

Third-Party State Management Libraries

For complex state management needs, especially in large applications, third-party libraries such as Redux, MobX, and Recoil can be used.


Example: Redux

Redux is a popular library for managing global state. It follows the principles of a single source of truth, immutability, and pure reducers.


Steps to Set Up Redux

  • Install Redux and React-Redux
npm install redux react-redux
  • Create Redux Store and Reducer
// store.js
import { createStore } from 'redux';

const initialState = { count: 0 };

function reducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
}

const store = createStore(reducer);

export default store;
  • Provide the Store to Your Application
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
  • Connect Components to the Redux Store
// App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

function App() {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
    </div>
  );
}

export default App;

Summary

State management in React can range from simple local state management within a single component to complex global state management across a large application. Understanding when and how to use local state, lifting state up, Context API, and third-party libraries like Redux is crucial for building scalable and maintainable React applications.

Further, if you have any questions, please visit our website, Gurulabs Website Design Agency.