Best Possible way to pass value within components in React

Rizwan
2 min readMar 28, 2023

--

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 for more tips and tricks like this.
Please like and subscribe me to stay up to date with my latest articles on different topics.

Thank you !

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Rizwan
Rizwan

Written by Rizwan

Senior Software Engineer | Mentor | Tech Enthusiast | Passionate about building scalable solutions, exploring the latest technologies.

No responses yet

Write a response