DEV Community

JC
JC

Posted on

1 1

Part 2. Sharing data between siblings components using Context in React with Hooks

Once we've got a context provider defined and in place it's time to make the data available on any child component. For this we will use a hook called useContext.

"useContext accepts a context object and returns the current context value for that context. The current context value is determined by the value prop of the nearest above the calling component in the tree". What this means is this hook will give us access to the prop passing the context defined by the context function and wrap in the provider. Let's see it in the component.


import React, { useContext } from "react";



function Profile()  {

    const pots = useContext(PostContext)
    const setPots = useContext(PostDispatchContext)



   return (
        <> 
   {posts.map(post => <h2>{post}</h2>)}
       </> 

      );
}

export { Profile }


Enter fullscreen mode Exit fullscreen mode

First we import useContext from the react library. Then we define our props calling the hook and passing the context created for the prop. In this case for posts we created PostContext to query the context state and PostDispatchContext to mutate the context state. This will give us access to the props state set as an empty array at first.

And finally we can return the data we need. It's important to notice that setPosts is a function as de-structured. When using it to update posts it expects an object that we can easily iterate as a list of posts.

Context provides a way to pass data through the component tree from parent to child components, without having to pass props down manually at each level. It's specially useful to pass data deeply and great tool as a global state management.

While React Context is native and simple to set, it isn’t a dedicated state management tool like Redux, however it can be really useful for prop drilling.

Thanks for reading..

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay