Home > Back-end >  I believe I have created a shareable state using useReducer only, I need advice if this is wrong
I believe I have created a shareable state using useReducer only, I need advice if this is wrong

Time:10-30

Store.js:

import {useReducer} from "react";
import {ACTION_TYPES} from "./storeActionTypes";

export const INITIAL_STATE = {
  counter: 0,
};

export const storeReducer = (state, action) => {
  switch (action.type) {
    case ACTION_TYPES.INCREASE_COUNTER_BY_1:
      return {
        ...state,
        counter: state.counter   1,
      };
    default:
      return state;
  }
};

const Store = () => {
  const [state, dispatch] = useReducer(storeReducer, INITIAL_STATE);
  return [state, dispatch];
};

export default Store;

AnyComponent.js

import React from "react";
import Store from "../store/Store";

const AnyComponent = () => {
  const [store, dispatch] = Store();

  const handleInceaseByOne = (e) => {
    e.preventDefault();
    dispatch({type: "INCREASE_COUNTER_BY_1"});
  };

  return (
    <div>
      <button onClick={(e) => handleInceaseByOne(e)}>Submit</button>
      <span>counter from AnyComponent.js:{store.counter}</span>
    </div>
  );
};

export default AnyComponent;

OtherComponent.js

import React from "react";
import Store from "../store/Store";

const OtherComponent.js = () => {
  const [store, dispatch] = Store();

  return (
    <div>
      <span>counter from OtherComponent.js:{store.counter}</span>
    </div>
  );
};

export default OtherComponent.js;

So basically like in Redux, create a one Store where you store everything. In AnyComponent.js we have button who increase counter by 1 so we can see that value of store.counter in AnyComponent.js and OtherComponent.js.
Please anyone tell me if anything is wrong with this code?
Will try to upload this to GitHub later.

I looked in web and did not found anything what is similar to this so please let me know what you think.

CodePudding user response:

If you actually try this one, you will see that the counter state of one component does not reflect on the second one. You haven't created a single state but 2 separate ones.

Since you call Store() in each component which leads to a new call to useReducer, you create a new instance of this reducer/state which is standalone and can only be used from the component where it's called (or it's children if passed down as props).

What you've done here is to create your own custom hook and this is used for re-usability only and not shared state. Shared state can be achieved through a lot of other alternatives (such as react context).

Feel free to check this out in this reproducable codesandbox.

CodePudding user response:

From the React Docs:

"Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks — your own custom Hooks. [...]." (https://reactjs.org/docs/hooks-overview.html)

  • Related