0
Is there any way we can access a variable of another functional component in React?
For example I have a variable which stores date in specific format and I need it in several components. Can I just declare it in one component (e.g App.js) and also access it from a different component?
2 Answers
+ 7
What Schindlabua is suggesting is a valid solution, but there are few other solutions that might be more suitable depending on the use case and the application complexity.
An alternative is to use a state management such as Redux, MobX, Recoil, ..... (there are many others out there).
Here's some extra reading for you:
https://areknawo.com/top-5-react-state-management-libraries-in-late-2020/
https://daveceddia.com/react-state-management/
https://dev.to/thatanjan/top-5-state-management-libraries-for-react-2c9
Another alternative is the Context API which you can learn more about in here:
https://www.google.com/amp/s/www.freecodecamp.org/news/react-context-for-beginners/amp/
+ 3
You need to move that variable up in the component hierarchy and then pass it as a property to other components.
const App = () => {
const date = new Date();
return (<DateContainer date={date} />);
};
const DateContainer = ({ date }) => {
return (
<div> { date.toString() } </div>
);
}