DEV Community

KentaroMorishita
KentaroMorishita

Posted on

Simplifying State Management in React: An Introduction to F-Box React

"Oh no… my state is a mess again."

When managing state with React, have you ever encountered issues like these?

  • While useState and useReducer are convenient, passing state around becomes cumbersome as the number of components increases.
  • To share state among multiple components, you often resort to prop drilling or introducing useContext.
  • Libraries like Redux are powerful but come with a steep learning curve.

"Isn't there a simpler way to manage state?"

That's why I created F-Box React.
With F-Box React, you can break free from state management boilerplate and keep your code simple!

Table of Contents

  1. Introduction
  2. Basic Example: Counter App
  3. RBox: Usable Outside of React
  4. Sharing State Across Multiple Components
  5. Using useRBox as a Replacement for useReducer
  6. Details and Background of F-Box React
  7. Conclusion

Introduction

Let's start by looking at concrete code examples to understand how to use F-Box React. In this section, we'll compare useState with useRBox using a simple counter app as an example.

Basic Example: Counter App

The Usual React Way (useState)

import { useState } from "react"

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

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

export default Counter
Enter fullscreen mode Exit fullscreen mode

This classic approach uses useState to manage the count.

Using F-Box React

import { useRBox, set } from "f-box-react"

function Counter() {
  const [count, countBox] = useRBox(0) // Create an RBox with initial value 0
  const setCount = set(countBox) // Get a convenient updater function for the RBox

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

export default Counter
Enter fullscreen mode Exit fullscreen mode

Here, we implement the counter using useRBox. Since useRBox returns a [value, RBox] pair, it can be used very similarly to useState.

RBox: Usable Outside of React

import { RBox } from "f-box-core"

const numberBox = RBox.pack(0)

// Subscribe to changes and log updates
numberBox.subscribe((newValue) => {
  console.log(`Updated numberBox: ${newValue}`)
})

// Change the value, which notifies subscribers reactively
numberBox.setValue((prev) => prev + 1) // Updated numberBox: 1
numberBox.setValue((prev) => prev + 10) // Updated numberBox: 11
Enter fullscreen mode Exit fullscreen mode

As shown above, RBox does not depend on React, so it can be used for reactive data management in any TypeScript code.

Sharing State Across Multiple Components

The Usual React Way (with useContext)

import React, { createContext, useContext, useState } from "react"

const CounterContext = createContext()

function CounterProvider({ children }) {
  const [count, setCount] = useState(0)
  return (
    <CounterContext.Provider value={{ count, setCount }}>
      {children}
    </CounterContext.Provider>
  )
}

function CounterDisplay() {
  const { count } = useContext(CounterContext)
  return <p>Count: {count}</p>
}

function CounterButton() {
  const { setCount } = useContext(CounterContext)
  return <button onClick={() => setCount((prev) => prev + 1)}>+1</button>
}

function App() {
  return (
    <CounterProvider>
      <CounterDisplay />
      <CounterButton />
    </CounterProvider>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

This method uses useContext to share state, but it tends to make the code verbose.

Using F-Box React

import { RBox } from "f-box-core"
import { useRBox } from "f-box-react"

// Define a global RBox
const counterBox = RBox.pack(0)

function CounterDisplay() {
  const [count] = useRBox(counterBox)
  return <p>Count: {count}</p>
}

function CounterButton() {
  return (
    <button onClick={() => counterBox.setValue((prev) => prev + 1)}>+1</button>
  )
}

function App() {
  return (
    <div>
      <CounterDisplay />
      <CounterButton />
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Here, we define a global RBox and use useRBox in each component to share state. This avoids the need for useContext or providers, keeping the code simple.

Using useRBox as a Replacement for useReducer

The Usual React Way (with useReducer)

import { useReducer } from "react"

type State = {
  name: string
  age: number
}

type Action =
  | { type: "incremented_age" }
  | { type: "changed_name"; nextName: string }

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "incremented_age": {
      return {
        name: state.name,
        age: state.age + 1,
      }
    }
    case "changed_name": {
      return {
        name: action.nextName,
        age: state.age,
      }
    }
  }
}

const initialState = { name: "Taylor", age: 42 }

export default function Form() {
  const [state, dispatch] = useReducer(reducer, initialState)

  function handleButtonClick() {
    dispatch({ type: "incremented_age" })
  }

  function handleInputChange(e: React.ChangeEvent<HTMLInputElement>) {
    dispatch({
      type: "changed_name",
      nextName: e.target.value,
    })
  }

  return (
    <>
      <input value={state.name} onChange={handleInputChange} />
      <button onClick={handleButtonClick}>Increment age</button>
      <p>
        Hello, {state.name}. You are {state.age}.
      </p>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Using F-Box React

import { useRBox, set } from "f-box-react"

function useUserState(_name: string, _age: number) {
  const [name, nameBox] = useRBox(_name)
  const [age, ageBox] = useRBox(_age)

  return {
    user: { name, age },
    changeName(e: React.ChangeEvent<HTMLInputElement>) {
      set(nameBox)(e.target.value)
    },
    incrementAge() {
      ageBox.setValue((prev) => prev + 1)
    },
  }
}

export default function Form() {
  const { user, changeName, incrementAge } = useUserState("Taylor", 42)

  return (
    <>
      <input value={user.name} onChange={changeName} />
      <button onClick={incrementAge}>Increment age</button>
      <p>
        Hello, {user.name}. You are {user.age}.
      </p>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

By using useRBox, you can manage state without defining reducers or action types, simplifying the code.

Details and Background of F-Box React

So far, we've introduced the basic usage of F-Box React through code examples. Next, we'll cover the following detailed information:

  • Background: Why Was F-Box React Created?
  • Core Concepts (Details about RBox and useRBox)
  • Installation and Setup Instructions

These points are crucial for a deeper understanding of F-Box React.

Background: Why Was F-Box React Created?

Originally, I developed F-Box (f-box-core) purely as a general-purpose library for functional programming. F-Box provides abstractions like Box, Maybe, Either, and Task to simplify data transformations, side effects, and asynchronous computations.

Within F-Box, a reactive container named RBox was introduced. RBox monitors changes in its value and enables reactive state management.

After creating RBox, I thought, "What if I integrate this reactive box into React? It could simplify state management in React applications." Based on this idea, I developed F-Box React (f-box-react)—a collection of hooks that make it easy to use RBox within React components.

As a result, F-Box React turned out to be surprisingly user-friendly, providing a powerful tool to manage state in React in a simple and flexible manner.

Core Concepts

The key elements of F-Box React are:

  • RBox
    A container that enables reactive state management. It can observe and manage state changes independently of React.

  • useRBox
    A custom hook to easily use RBox within React components. It provides an intuitive API similar to useState, allowing you to retrieve and update reactive values.

These elements mean that:

  • Feels like useState
    Handling state is as intuitive as with useState.

  • Effortlessly share state across multiple components
    You can easily share state between multiple components.

  • RBox can be used outside React too
    Because it doesn't depend on React, it's usable in non-React environments as well.

This makes state management extremely simple.

Installation and Setup Instructions

To integrate F-Box React into your project, run the following command using npm or yarn. Since F-Box React depends on f-box-core, you must install both simultaneously:

# If you're using React 19 (latest version)
npm install f-box-react f-box-core

# If you're using React 18
npm install f-box-react@0.1 f-box-core
Enter fullscreen mode Exit fullscreen mode

After installation, you can import and use hooks like useRBox as shown in the earlier examples:

import { useRBox } from "f-box-react"
Enter fullscreen mode Exit fullscreen mode

Also, ensure that f-box-core is installed, as it provides the essential containers like RBox:

import { RBox } from "f-box-core"
Enter fullscreen mode Exit fullscreen mode

With this setup, you can now manage state using F-Box React.

Conclusion

By using F-Box React, state management in React becomes significantly simpler:

  1. Intuitive like useState
    Just pass an initial value to useRBox and start using it immediately.

  2. RBox works outside of React
    Because it doesn't depend on React, you can use it on the server side or in other environments.

  3. Easy state sharing
    Define a global RBox and use useRBox wherever you need it to share state across multiple components. This eliminates the need for complex setups with useContext or Redux.

If you're looking for a simpler way to manage state, give F-Box React a try!

We've introduced the basic usage and convenience of F-Box React here, but F-Box offers many more features. It can handle asynchronous operations, error handling, and more complex scenarios.

For more details, see the F-Box Docs.
I hope F-Box React makes your React and TypeScript development more enjoyable and simpler!

Top comments (0)