skip to Main Content

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


  1. You can pass data from one component to another through 3 ways:-

    1. By passing data as a prop. One way*(Only from parent component to child)*
    2. By using useContext Hook. Both way(From parent to child and child to parent)
    3. User react-redux. (Accessible over all routes) same as 2.
    Login or Signup to reply.
  2. 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

    import React, { useState } from 'react';
    import Child from './Child';
    
    function Parent() {
        const [loginData, setLoginData] = useState();
    
        return (
            <div>
                <Child data={loginData} />
            </div>
        )
    }
    
    export default Parent
    

    in Child.tsx

    import React from 'react';
    
    function Child(props: { data: any }) {
        return <p>props.data</p>
    }
    
    export default Child
    

    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.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search