logo

Simplifying React State Management with SWR

Managing state in React applications is a crucial aspect of development, and finding a balance between simplicity and efficiency becomes key to a robust codebase. If you're already using SWR for data fetching and find yourself in need of a straightforward state management alternative to Redux or similar libraries, SWR might be the solution for you.

Before diving into the details, make sure to install SWR if you haven't already

    npm install swr

    

While this custom hook provides a lightweight solution for simple state management, it may not be suitable for handling complex state structures. If your application requires intricate state management with advanced features, consider more robust solutions like Redux or similar libraries.

Now, let's dive into the code for the custom hook:

    import useSWR from 'swr';

export default function useSharedState(key, initialValue) {
  const { data: state, mutate: setState } = useSWR(key, {
    fallbackData: initialValue,
  });

  return [state, setState];
}

    
state/index.js

This hook is designed to manage shared state across components, utilizing the caching and reactivity features provided by SWR.

The key parameter represents the unique identifier for the shared state. The initialValue parameter sets the initial value of the state.

The hook employs SWR to manage the state with the given key. The fallbackData option ensures that the state starts with the specified initial value.

The hook returns an array containing the current state state and a mutator function setState. state represents the current value of the shared state. setState is a function that allows you to update the shared state, triggering a re-render.

Let's see how you can use in a React component:

    import useSharedState from '../state';

export default function ExampleComponent() {
  const [sharedState, setSharedState] = useSharedState('exampleKey', 'initialValue');

  const handleUpdateState = () => {
    // Update the shared state using the mutator function
    setSharedState('newUpdatedValue');
  };

  return (
    <div>
      <p>Shared State: {sharedState}</p>
      <button onClick={handleUpdateState}>Update State</button>
    </div>
  );
}

    
component/example.jsx

In this example, ExampleComponent uses the useSharedState hook to manage a shared state with the key exampleKey and an initial value of initialValue. The component renders the shared state and provides a button to trigger an update using the mutator function.

The useSharedState hook provides a seamless integration of React's simplicity with the robust data fetching capabilities of SWR, presenting an elegant solution for managing shared state in your React applications. If you're utilizing TanStack Query as your data fetching library, adapting the custom hook is achievable with minor adjustments.