0

I want to pass an array of numbers from one component to another (from one page to another) in my React app, by using onClick of a button. I currently do it using state and "useLocation" from 'react-router-dom". It works, but I'm not sure if this is the most efficient way to do it. The array that I'm passing can be up to a 1,000 elements long. Could anyone advise me on what is the best practice here?

Here's how I pass the data:

function onClickExample() {
        navigate(REVIEW, {state: {IDs: dueReviewIDs}})
}

Here's how I retrieve data:

const { state } = useLocation();
const IDs = state.IDs;

I have read other answers, but they don't focus on the specific case of passing data using onClick (rather than simply passing parameter to a child component). (For example: How to pass an array of items in React.js)

Would, for exmample, using LocalStorage be a more reliable option?

  • 1
    use **ContextAPI** to create a global variables to be used wherever you want in your app – monim Jun 04 '23 at 15:48
  • Thank you, @monim! I didn't know about it. Reading more about Context raised additional questions though. I found this: "Keep Context API limited to global state management only: It's best to use the Context API for managing state that needs to be accessed across multiple components in your application. ". What happens in case where I use the data in a single component only, and not globally? So I only have to pass the data to one component, althought it's not a child. Is context still the best option? Thank you! – u4ii4y984484y203r Jun 04 '23 at 16:19
  • 1
    well, it's true **contextAPI** is better when you want to manage state globally in other words when you need tot access the state in the entire app or in many components , and use props when it's limited to child components or grandChild not deeply to avoid props drilling . in your case I guess the best approach is what you did – monim Jun 04 '23 at 16:25
  • 1
    See [How to pass data from a page to another page...](https://stackoverflow.com/a/59701168/8690857). Passing it in route state seems fine to me. If you are specifically asking what is "the best" practice, well this is subjective and likely off-topic – Drew Reese Jun 05 '23 at 16:05

0 Answers0