Search code examples
reactjsredux

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/>
    </>
}

Solution

  • 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.