npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-branch-provider

v0.5.0

Published

State management and a low boilerplate way to separate business logic from components in React

Downloads

3,375

Readme

React Branch Provider

What is rbp?

Built on top of React Context API, rbp inherits its capabilities and extends them by adding a way of updating the state while making it immutable.

It fits right into a Component-Based Architecture by offering a low boilerplate way to separate state management and business logic from the UI, while keeping everything on the same module.

- App.jsx
- components
  - Posts
    - posts.provider.js
    - Posts.css
    - Posts.jsx
    - PostsList.tsx

By containing the state management logic on a certain tree level, future you won't have to worry about affecting other parts of the app that you may not remember, or even ever heard of.

Unlike with global state management, you only worry about that branch. If the branch gets unmounted, the state goes away, if the branch gets scratched from the project, the state management logic goes away with it, and if the implementation is modified, it is less likely to have unintended consecuences.

Install

npm i react-branch-provider

yarn add react-branch-provider

Easy to implement

// components/Posts/posts.provider.js

import { createProvider } from "react-branch-provider";

export const postsProvider = createProvider({ posts: [] });

export const getPosts = async () => {
  const posts = await fetchPosts();

  postsProvider.setState((state) => {
    state.posts = posts; // it's safe to mutate the state
  });
};
// App.jsx

import { Provider } from "react-branch-provider";
import { postsProvider } from "./components/Posts/posts.provider";
import Posts from "./components/Posts/Posts";

function App() {
  return (
    <Provider state={postsProvider}>
      <Posts />
    </Provider>
  );
}
// components/Posts/Posts.jsx
import PostsList from "./PostsList";

function Posts() {
  return (
    <article>
      <h2>Posts</h2>

      <PostsList />
    </article>
  );
}
// components/Posts/PostList.jsx

import { useBranchState } from "react-branch-provider";
import { postsProvider, getPosts } from "./posts.provider";

function PostList() {
  const state = useBranchState(postsProvider);

  useEffect(() => {
    getPosts().catch(error => console.error(error));
  }, []);

  return (
    <ul>
      {state.posts.map(post => (
        <li key={post.id}>{post.title}</li>
      )}
    </ul>
  );
}

Selectors

Get only what you need, it's cleaner.

// components/Posts/posts.provider.js
...
export const selectPosts = state => state.posts;
// components/Posts/PostList.jsx
...
import { ..., selectPosts } from "./posts.provider";

function PostList() {
  const posts = useBranchState(postsProvider, selectPosts);
  ...
}

Immutable state

Thanks to immer, rbp allows for easy state manipulation. You don't need to worry about it, just go crazy!

someStateProvider.setState((state) => {
  for (const post of state.posts) {
    if (post.id === postId) {
      post.owner = userId;
      state.users[userId].posts.push(post);
      break;
    }
  }
});

Alternatively, you can return a new state entirely, the old fashion way.

someStateProvider.setState((state) => {
  return {
    ...state,
    // write the same changes here ;)
  };
});

Nesting providers

Since rbp is built on top of React Context API this is an easy task.

// you can go like

function App() {
  return (
    <Provider state={themeProvider}>
      <Provider state={authProvider}>
        <Posts />
      </Provider>
    </Provider>
  );
}

MultiProvider

rbp extends the nesting capabilities by allowing to pass multiple providers to a single component.

// this looks cleaner

function App() {
  return (
    <MultiProvider states={[themeProvider, authProvider]}>
      <Posts />
    </MultiProvider>
  );
}

Multi paradigm support.

I like functions

export const postsProvider = createProvider({ posts: [] });

export const getPosts = async () => {
  const posts = await fetchPosts();

  postsProvider.setState((state) => {
    state.posts = posts;
  });
};

I like classes

class PostsProvider extends BranchProvider {
  async getPosts() {
    const posts = await fetchPosts();

    this.setState((state) => {
      state.posts = posts;
    });
  }
}

export const postsProvider = new PostsProvider({ posts: [] });

Tooling

There is a Google Chrome extension to help us visualize the current providers' state.

To enable this tool add the following snippet as soon as possible in your codebase:

import { enableDevTools } from "react-branch-provider";

// Invoking this function will connect your app and display your providers' state on the tool's UI
enableDevTools();

// Consider enabling these tools for development environments only
if (process.env.NODE_ENV === "development") {
  enableDevTools();
}

Naming providers

Providers on this tool can be either named on unnamed.

To name a functional provider the factory function takes a optional second paramenter.

function createProvider(state: any, name?: string): BranchProvider;

Class providers are automatically named with their constructor name. To override this behavior the constructor takes an optional second parameter.

class PostsProvider extends BranchProvider {}

new PostsProvider({ posts: [] }); // will be named PostsProvider

new PostsProvider({ posts: [] }, "Posts"); // will be named Posts