Dima Kambalin
Dima Kambalin

Reputation: 357

How to pass value of state variable from one component to a sibling component?

I want to pass state variable from Filter to PaginatedTable component. How to impement it? Maybe I should use redux? (I have no idea how redux works, but I heard it is used to manage state of application)

import React from "react";

function CompanyTable(): JSX.Element{

    return <>
        <Filter/>
        <PaginatedTable/>
    </>
}

Upvotes: 0

Views: 107

Answers (2)

Jimmy-P
Jimmy-P

Reputation: 151

Redux seems like overkill for this simple use case, particularly if you have to learn redux first.

I assume you have a state variable and a function to set the state variable in your Filter component, and you want the value to be available in your PaginatedTable component. Using hooks, I would do it this way

import React, { useState } from "react";

function CompanyTable(): JSX.Element{
    const [yourVariable, setYourVariable] = useState(yourVariablesInitialState)
    return <>
        <Filter setYourVariable={setYourVariable}/>
        <PaginatedTable yourVariable={yourVariable}/>
    </>
}

You can now call props.setYourVariable in your Filter component and the value you pass will be available in your PaginatedTable component. And you no longer need to have the variable in the Filter component's state. If you also want to have it there, you can pass it down as a prop as with PaginatedTable. You should change the names from my example as those names are pretty bad.

Upvotes: 1

Harsh Gaur
Harsh Gaur

Reputation: 39

There are various ways to go about it, you can decide based upon your needs. If you have a very basic application, then passing the state as props can help.

If you have an application like a complex to-do list or anything of that scale you can use context API.

Or, If you have a very large application like an e-commerce website where you have to share many states or your states are dynamic in nature then you can use redux.

Here are the links for your reference.

  1. Passing states as props
  2. Managing state as Context API
  3. Managing state with Redux

Upvotes: 1

Related Questions