Back to Next JS Course

Next JS Course

State management is a crucial aspect of building dynamic web applications. In Next JS, state can be managed at different levels using various tools and techniques, from React's built-in hooks to more advanced libraries.

React Built-in State Management

useState Hook

The useState hook allows you to add state to functional components.

For example,

import { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }; export default Counter;

useEffect Hook

The useEffect hook lets you perform side effects in functional components.

For example,

import { useState, useEffect } from 'react'; const Timer = () => { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { setSeconds((prev) => prev + 1); }, 1000); return () => clearInterval(interval); }, []); return <p>Seconds: {seconds}</p>; }; export default Timer;

Context API

Creating a Context

The Context API allows you to create global state that can be accessed by any component in the application.

For example,

import { createContext, useState, useContext } from 'react'; const ThemeContext = createContext(); export const ThemeProvider = ({ children }) => { const [theme, setTheme] = useState('light'); return ( <ThemeContext.Provider value={{ theme, setTheme }}> {children} </ThemeContext.Provider> ); }; export const useTheme = () => useContext(ThemeContext);

Using Context in Components

For example,

import '../styles/globals.css'; import { ThemeProvider } from '../context/ThemeContext'; function MyApp({ Component, pageProps }) { return ( <ThemeProvider> <Component {...pageProps} /> </ThemeProvider> ); } export default MyApp;
import { useTheme } from '../context/ThemeContext'; const ThemeSwitcher = () => { const { theme, setTheme } = useTheme(); return ( <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}> Switch to {theme === 'light' ? 'dark' : 'light'} mode </button> ); }; export default ThemeSwitcher;

Advanced State Management Libraries

Redux

A popular state management library for managing global state in large applications.

Installation npm install redux react-redux @reduxjs/toolkit

For example,

import { configureStore } from '@reduxjs/toolkit'; import counterReducer from './features/counter/counterSlice'; export const store = configureStore({ reducer: { counter: counterReducer, }, });
import { createSlice } from '@reduxjs/toolkit'; export const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: (state) => { state.value += 1; }, decrement: (state) => { state.value -= 1; }, }, }); export const { increment, decrement } = counterSlice.actions; export default counterSlice.reducer;
import '../styles/globals.css'; import { Provider } from 'react-redux'; import { store } from '../store'; function MyApp({ Component, pageProps }) { return ( <Provider store={store}> <Component {...pageProps} /> </Provider> ); } export default MyApp;
import { useDispatch, useSelector } from 'react-redux'; import { increment, decrement } from '../features/counter/counterSlice'; const Counter = () => { const count = useSelector((state) => state.counter.value); const dispatch = useDispatch(); return ( <div> <p>Count: {count}</p> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> ); }; export default Counter;