"Oh no… my state is a mess again."
When managing state with React, have you ever encountered issues like these?
"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!
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.
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
This classic approach uses useState to manage the count.
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
Here, we implement the counter using useRBox. Since useRBox returns a [value, RBox] pair, it can be used very similarly to useState.
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
As shown above, RBox does not depend on React, so it can be used for reactive data management in any TypeScript code.
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
This method uses useContext to share state, but it tends to make the code verbose.
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
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.
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> </> ) }
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> </> ) }
By using useRBox, you can manage state without defining reducers or action types, simplifying the code.
So far, we've introduced the basic usage of F-Box React through code examples. Next, we'll cover the following detailed information:
These points are crucial for a deeper understanding of F-Box React.
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.
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.
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:
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
After installation, you can import and use hooks like useRBox as shown in the earlier examples:
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
Also, ensure that f-box-core is installed, as it provides the essential containers like RBox:
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
With this setup, you can now manage state using F-Box React.
By using F-Box React, state management in React becomes significantly simpler:
Intuitive like useState
Just pass an initial value to useRBox and start using it immediately.
RBox works outside of React
Because it doesn't depend on React, you can use it on the server side or in other environments.
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!
The above is the detailed content of Simplifying State Management in React: An Introduction to F-Box React. For more information, please follow other related articles on the PHP Chinese website!