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-ducks

v0.6.3

Published

🦆 React ducks without Redux

Downloads

67

Readme

React Ducks

NPM badge Dependabot badge Dependencies Build Status Coverage Status

Implement ducks in React following the redux pattern but using React Context.

Uses immer to wrap reducers when creating, ensuring atomic state mutations.

Usage

Create the ducks for each slice of application logic.

// duck/counter.js
export default createDuck({
  name: "counter",
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
  },
  actionMapping: { otherActionType: "increment" },
  selectors: { current: (namespacedState) => namespacedState["counter"] },
});

Note: The current selector is just an example. In an actual implementation it would be made redundant by $ which is created by default for all ducks to fetch the namespaced state.

counterDuck.selectors.$(state);
// this is equivalent to (rootState) => rootState[counterDuck.name]

Create the root/global duck as a combination of all other ducks.

// duck/index.js
export default createRootDuck(counterDuck, otherDuck);

Create the global context.

// context.js
export default createContext(
  rootDuck.reducer,
  rootDuck.initialState,
  enhancer,
  "ContextName",
  useAsGlobalContext
);

Note: The enhancer may be optionally specified to enhance the context with third-party capabilities such as middleware, time travel, persistence, etc. The only context enhancer that ships with Ducks is applyMiddleware.

Note: The useAsGlobalContext i.e. global option; allows for setting a default context that is used by the useDispatch and useSelector hooks when no Context is supplied. This is useful when creating the context that will be used with the root provider.

Use the state and actions in your component.

// app.jsx
export default function App(props) {
  const { state, dispatch } = React.useContext(Context);
  const count = counterDuck.selectors.$(state);
  const increment = React.useCallback(
    () => dispatch(counterDuck.actions.increment()),
    [dispatch]
  );
  return (
    <div>
      Count: <span>{count}</span>
      <button onClick={increment} />
    </div>
  );
}

Note: The use of React.useContext can be replaced with a combination of useDispatch and useSelector hooks.

// app.jsx
...
  const count = useSelector(counterDuck.selectors.$, Context);
  const increment = useDispatch(counterDuck.actions.increment, Context);
...

Note: This is equivalent to the class component described below.

// app.jsx
export default class App extends React.PureComponent {
  static contextType = Context;

  render() {
    const { state } = this.context;
    return (
      <div>
        Count: <span>{counterDuck.selectors.$(state)}</span>
        <button onClick={this.increment} />
      </div>
    );
  }

  increment = () => {
    this.context.dispatch(counterDuck.actions.increment());
  };
}

Wrap the application in the root provider to handle state changes.

// index.jsx
const rootElement = document.getElementById("root");
const Provider = createRootProvider(Context);
ReactDOM.render(
  <Provider>
    <App />
  </Provider>,
  rootElement
);

Note: createRootProvider is just a helper and can be replaced, with the functional difference highlighted below.

// index.jsx
const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider Context={Context}>
    <App />
...

A side benefit to scoping the context state to the provider is allowing multiple entire apps to be run concurrently.

applyMiddleware(...middlewares)

This takes a variable list of middlewares to be applied.

Example: Custom Logger Middleware

// context.js
function logger({ getState }) {
  // Recommend making the returned dispatch method asynchronous.
  return (next) => async (action) => {
    console.log("will dispatch", action);
    // Call the next dispatch method in the middleware chain.
    const returnValue = await next(action);
    // Resolving the result of the next dispatch allows the referenced
    // state to be updated by `React.useReducer` and available to get.
    console.log("state after dispatch", getState());
    // This will likely be the action itself, unless
    // a middleware further in chain changed it.
    return returnValue;
  };
}

export default createContext(..., applyMiddleware(logger));

See redux applyMiddleware for more documentation.

Demo

As a proof of concept see the converted sandbox app from the react-redux basic tutorial below.

References

Lots of inspiration from the following tools