Skip to content

Simple Flux architecture for React applications, allowing to use Hooks and access/edit from anywhere. Designed for small projects. Code improvements are welcome.

Notifications You must be signed in to change notification settings

LuisAguadoVicaria/flux-with-hooks-react

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Flux with hooks in React

Simple Flux architecture for React applications, allowing to use Hooks and access/edit from anywhere. Designed for small projects. Code improvements are welcome.

live-demo

JavaScriptReactNode.js

Flux.js

import { useState, useNavigate } from "react";

/** Use any React Hook of your choice */

const useFlux = () => {
  const [store, _setStore] = useState({
    /** Global store objects. */
    hide: false,
    var1: "val1",
    save: { any: "obj" },
  });

  const setStore = (obj) => _setStore({ ...store, ...obj });
  return {
    actions: {
      /** Global functions. */
      /** Example of a global function. */
      hideTextToggle: () => {
        /** Set and access Flux within Flux. */
        setStore({ hide: !store.hide });
      },
    },
    store: store,
    setStore: (obj) => setStore(obj),
  };
};

export default useFlux;

index.js

...

/** Import useFlux and define the global context. */
import useFlux from "./Flux";
const AppContext = React.createContext();

...

/** Wrap the context and inject useFlux(). */
const Index = () => (
  <AppContext.Provider value={useFlux()}>
    <App />
  </AppContext.Provider>
);

...

/** Export the context as React custom hook. */
export const useAppContext = () => useContext(AppContext);

anycomponent.js

/** Import the global context. */
import { useAppContext } from "./index";

...

  /** Declare helpers to manipulate the context. */
  const { store, setStore, actions } = useAppContext();
  
...

/** Change or set your global variables. */
         ... onClick={() => setStore({ var1: "val1-changed", adding: "another" })}
          
...

/** Call your global functions. */
         ... onClick={() => actions.hideTextToggle()}

Deployment

  • Assuming you have installed Node.js locally, run: npm install
  • Run: npm run start to start development server and test the live web site.
  • Run: npm run build to compile the site for production.
  • Look for the /build folder.
  • Make sure the HTML and JS paths are correct and install the site on your preferred web server.

You can also open any GitHub repository in Gitpod

Open in Gitpod

Contact

Feel free to leave me a message, I'm friendly!

LinkedIn

About

Simple Flux architecture for React applications, allowing to use Hooks and access/edit from anywhere. Designed for small projects. Code improvements are welcome.

Topics

Resources

Stars

Watchers

Forks