Skip to content
Advertisement

How to import an useState object from another folder

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?

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement