Home > Blockchain >  How to import an useState object from another folder
How to import an useState object from another folder

Time:04-29

I have a project which created in "Creat React App" and i have an useState array which looks like this:

const [State, setState] = useState([]);

This array is in another folder inside a component called StateComp, but i also want to load this array in the main folder (App.js for this case).

I tried to just import the State and the setState from the StateComp file into the App.js file, but as i expected, the import itself failed.

Anyone have any idea?

CodePudding user response:

You can use custom hooks for this! You can see an example of this here: https://stackoverflow.com/a/72048200/8222441 and an example of it being called in another file here: https://stackoverflow.com/a/72048200/8222441

Here is a quick solution to help in the meantime:

import { useState, useEffect } from 'react';

export function useSomeState(someParam) {
  const [someState, setSomeState] = useState([]);

  useEffect(() => {
    // do some state logic here if you want
  });

  return { someState, setSomeState };
}

// in another file...

import { useSomeState } from './useSomeStateFile.js'

function SomeComponent = () => {
   const { someState, setSomeState } = useSomeState(someParam)
}

CodePudding user response:

You can use React Context to manage this or Redux. Here's an example with React Context:

src/providers/StateProvider.js

import React, { useContext, useState } from "react";

import { createContext } from "react";

const StateContext = createContext({
  state: [],
  setState: () => {},
});

export const useStateContext = () => useContext(StateContext);

const StateProvider = ({ children }) => {
  const [state, setState] = useState([]);

  return (
    <StateContext.Provider value={{ state, setState }}>
      {children}
    </StateContext.Provider>
  );
};

export default StateProvider;

src/App.js

import React from "react";
import { useStateProvider } from "./providers/StateProvider";

export default App = () => {
  const { state, setState } = useStateProvider();

  return <h1>MyApp</h1>;
};

src/index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import StateProvider from "./providers/StateProvider";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <StateProvider>
      <App />
    </StateProvider>
  </React.StrictMode>
);

reportWebVitals();
  • Related