I have a React component in which I receive data. But I want to use this data in another component as well. What is the best way to do this? I don’t want to use the child parent method like in the React documentation. What is the best way to do this?
fetch("http://localhost:3001/login")
.then((res) => res.json())
.then((data) => {
setData(data);
console.log(data);
});
In this component I am getting the data and I want to use it in the next component
import React from 'react'
function test() {
return (
<div>test</div>
)
}
export default test
In addition I don’t want to use the localstorge of the browser because of safety reasons
I want to transfer the data and I don’t want to have any tags in the return section.
3
Answers
You can pass data from one component to another through 3 ways:-
There are different methods for what you want to achieve, but with no doubt the best one, particularly in this situation, is using props.
You can use props to transfer data from parent to child component like this:
in Parent.tsx
in Child.tsx
Props is a really important concept to learn as a react developer, since they are the fundamental of communication between parent and child components.
Another way to pass data from a component to another is using Context, but it’s slightly more advanced and it’s usually used for global data.
You can use React Context API, Redux, or Mobx. Redux is recommended for large projects, while Mobx is useful and easy to use for simpler operations.