Search code examples
reactjsreact-hookscomponentsreact-props

Can I use a value inside a component in another component in React hooks (function component)?


component1.js

const component1= (props) => {
     const [**selectedCountry**, setSelectedCountry] = useState();
         <Dropdown onSelect={eventKey => {
          const { code } = countries.find(({ code }) => eventKey === code);
setSelectedCountry(eventKey);
setToggleContents(<><FlagIcon code={code} /> </>);
         }}
       >                            
<Dropdown.Menu>
 {countries.map(({ code, title }) => (
<Dropdown.Item key={code} eventKey={code}><FlagIcon code={code} /> {title}</Dropdown.Item>
   ))}
 </Dropdown.Menu>
</Dropdown>
    .
    .
    }

a variable within this component. It becomes setSelectedCountry according to the dropdown change. how can i get this value in component2.js (i need selectedCountry value) ?

export default function component2() {

       useEffect(() => {
        
    postService.getLanguage(**HERE VALUE**).then((response)=>{
            setData(response.data);
        },
        (error) => {
            console.log(error);
        }
        );
}, []);

   ***I will take this value as a parameter and evaluate it in get (selectedCountry)How can I ***
}

Solution

  • Yes, you can use createContext and useContext function here: https://reactjs.org/docs/context.html

    Alternatively you can use Redux to help you manage states used by multiple components.