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

@witivio_teamspro/use-reducer

v3.1.2

Published

React useMagicReducer hook

Downloads

20

Readme

React useMagicReducer custom hook


Advantages compared to original useReducer hook

  • Immutable state : you can't update state manually, you have to use dispatch function.
  • No need to create types for reducer methods.
  • You can choose to render or not component when set state (render by default).
  • Access state and reducer functions of your component from top components.
  • The function setState allows to update state partially.
  • No need to create handlers, dispatch method can be called with a closure.

Example of usage

import React, {ReactElement} from "react";
import {MagicReducerObject, MagicReducerRef, useMagicReducer, useMagicReducerRef} from "@witivio_teamspro/use-reducer";

export type State = {
    isOpen: boolean,
    message: string,
}

export type Props = {
    externalRef: MagicReducerExternalRef<typeof reducer>,
}

export type DialogRef = Props["externalRef"];

export const Dialog = (props: Props): ReactElement | null => {
    const [state, dispatch] = useMagicReducer(reducer, initialState, props.externalRef);

    const style: CSSProperties = {
        display: state.isOpen ? "flex" : "none",
        position: "absolute",
        top: "50%",
        left: "50%",
        transform: "translate(-50%, -50%)",
        backgroundColor: "white",
        width: "200px",
        height: "200px",
        flexDirection: "column",
        color: "black"
    }

    return (
        <div style={style}>
            <button onClick={dispatch("close")}>Close X</button>
            {state.message}
        </div>
    )
}

export const initialState: State = {
    isOpen: false,
    message: "",
}

export const reducer = {
    open: ({setState}, [event]: [React.SyntheticEvent | undefined], message: string) => {
        event?.stopPropagation();
        setState({isOpen: true, message});
    },
    close: ({setState}) => {
        setState({isOpen: false});
    }
} satisfies MagicReducerObject<State>;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

const TopComponent = () => {
    const dialogRef = useMagicReducerRef(Dialog);

    return (
        <div>
            <Dialog externalRef={dialogRef}/>
            <button onClick={dialogRef.dispatch("open", "Hello world")}>
                Open dialog
            </button>
        </div>
    )
}

How to use props inside reducer functions ?

You just need to create a function for the reducer and pass props as argument, instead of having a simple object.

Here is an example:

export const Dialog = (props: Props): ReactElement | null => {
    const [state, dispatch] = useMagicReducer(reducer(props), initialState, props.externalRef);
    //...
}

export const reducer = (props: Props) => ({
    //...
    logProps: () => {
        console.log(props)
    }
}) satisfies MagicReducerObject<State>;

How to type correctly dispatch method in a pure function ?

Use the type MagicDispatch<typeof reducer> to type correctly the dispatch function.

Here is an example:

import {MagicDispatch} from "@witivio_teamspro/use-reducer";

const myFunction = (dispatch: MagicDispatch<typeof reducer>) => {
    dispatch({type: "logProps"});
}

How to type correctly magic reducer reference in a pure function ?

Use the type MagicReducerRef<typeof Component> to type correctly the reference.

Here is an example:

import {MagicReducerRef} from "@witivio_teamspro/use-reducer";

const myFunction = (dialogRef: MagicReducerRef<typeof Dialog>) => {
    dialogRef.dispatch("open")();
}