D Dev Notebook

React State Libraries

State Libraries

What is a state library?

A state library helps you manage and share data (state) in your application.

  • State = data that changes over time. Example: user input, shopping cart items, whether a modal is open, etc.

  • A state library gives you tools to:

    • Store the state
    • Update it
    • Reactively update your UI when the state changes
    • Often, also helps share state between many components

React State Library : Redux

1. Install Redux & React-Redux

npm install redux react-redux

2. Create your Redux store

// src/store.js
import { createStore } from 'redux';

// Initial state
const initialState = {
  count: 0
};

// Reducer function
function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// Create store
export const store = createStore(counterReducer);

3. Setup Provider in your App

Wrap your app with <Provider> to give Redux store access to all components.

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

4. Use Redux state & dispatch in components

  • useSelector to read state
  • useDispatch to send actions
// src/App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

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

  return (
    <div style={{ padding: '20px' }}>
      <h1>Simple Redux Counter</h1>
      <h2>Count: {count}</h2>
      <button onClick={() => dispatch({ type: 'increment' })}>+1</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-1</button>
    </div>
  );
}
  • When you click +1 or -1, it dispatches an action to Redux.
  • Redux reducer updates the state.
  • useSelector re-renders your component with the new count.

On this page