There are a few different ways to pass values between components in React, depending on the situation and the desired behavior. Here are some common approaches:

Props:

The most common way to pass values between components is through props. Props are used to pass data from a parent component to a child component. The child component can access the prop values through this.props or by using destructuring. For example:

// Parent component
function Parent() { const message = "Hello, world!"; return <Child message={message} />;
} // Child component
function Child(props) { return <div>{props.message}</div>;
}

Context:

Context is a way to pass data to a tree of components without having to pass props manually at every level. Context provides a way to share values like a theme, locale, or authentication status between components without having to explicitly pass a prop through every level of the tree. For example:

const MyContext = React.createContext(); // Parent component
function Parent() { return ( <MyContext.Provider value="Hello, world!"> <Child /> </MyContext.Provider> );
} // Child component
function Child() { const message = React.useContext(MyContext); return <div>{message}</div>;
}

State lifting:

Sometimes, you may need to pass data between components that are not directly related as parent and child. In this case, you can lift the state up to a common ancestor and pass it down as props. For example:

// Grandparent component
function Grandparent() { const [count, setCount] = React.useState(0); return ( <div> <Parent count={count} setCount={setCount} /> </div> );
} // Parent component
function Parent(props) { return ( <div> <Child count={props.count} setCount={props.setCount} /> </div> );
} // Child component
function Child(props) { return ( <div> <button onClick={() => props.setCount(props.count + 1)}> Increment count </button> </div> );
}

By following these approaches, you can pass values between components in React in a way that suits your use case and helps you build maintainable and scalable applications.

Follow me on Codementor for more tips and tricks like this.
Please like and subscribe me to stay upto date with my latest artciles on different topics.

Thank you !

Source: https://www.codementor.io/rizatech/best-possible-way-to-pass-value-within-components-in-react-2391p2rn1u