stack5 flow
stack5 flow

Reputation: 65

How to access state from another function

Basically I have a state variable in one component which is in a seperate folder

State.js
const [data, setData] = useState([])

folder structure

Components
State > State js
Manipulate > Manipulate js

Basically I want to be able to pass state from the state file in the state folder and be able to access state from the state js in the manipulate js folder.

Is this possible? What would be the best way to do so?

Thanks!

Upvotes: 0

Views: 5935

Answers (2)

Glen Carpenter
Glen Carpenter

Reputation: 412

It sounds to me that you are trying to create State that is accessible throughout you application. You have a few options, namely a system like Redux, but React ships with a built-in Context system you can utilize to share state throughout your application.

State.js

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

export const StateContext = createContext();

export const StateProvider = props => {
  const [data, setData] = useState();

  return (
    <StateContext.Provider value={[data, setData]}>
      {props.children}
    </StateContext.Provider>
  );
};

Manipulate.js

import React, { useContext } from "react";
import { StateProvider, StateContext } from "../State";

const Manipulate = ()=> {
const [data, setData] = useContext(StateContext);
  return (
    <div>
      <StateProvider>
        <div>{props.data}</div>
      </StateProvider>
    </div>
  );
}

export default App;

Upvotes: 2

Josh
Josh

Reputation: 575

Generally, the useState hook is used to add state to a functional component. This hook does not create a global state that can be accessed by other components (unless you explicitly pass the state item as a property to child components).

If the Manipulate.js component has been imported in State.js, you could pass the state to Manipulate in the below way:

<Manipulate data={data} />

The above would give you access to data in the manipulate component. You would need to ensure that data has been added as a property in the Manipulate.js file like below:

const Manipulate = ({data}) => {
   // Your code here
}

If you also needed the state setter in Manipulate.js, you would need to repeat the above steps and pass down the setData function as a property.


The above is fine in some cases; however, if you need global state (i.e state that's available in many different components) you may want to consider using the useContext hook (docs here) or Redux.

Upvotes: 1

Related Questions