Rajan Lagah
Rajan Lagah

Reputation: 2528

React is updating both child component when data linked to one child is changing

I have 2 component

  1. Shape
  2. video

And they are in 1 route ./home

And i have context for ./home route as

<Router>
  <div >
    <PContext>
      <Route exact path="/" component={home} />
    </PContext>
  </div>
</Router>

Now in home i have

...
function Home() {
  
    useEffect( ()=>{
        console.log('Rendered PDetect')
    })
    
    return (
        <div>
                <Video/>
                <Shape/>
        </div>
    );
}

export default Home;

And i have function in Video child ( to detect aspect ratio ) and it will update the value of aspect ratio in variable in PContext and shape component will use that value and display it.

...
const Shape = () => {

    const { ratio }  = useContext(PDataContext)

    console.log("ratio",ratio)
    useEffect( ()=>{
        console.log('Rendered Shape')
    })
      
    return (
       <span className="shape_circle" >1</span>
    )
}

export default Shape

And context file is

...  
export const PDataContext = createContext()

const PContext = ( props ) => {

   const [ ratio , setSetRatio ] = useState([])
  
  const gotRatio = r => {
    setSetRatio(r[0].key)
  }

  return(<PoseDataContext.Provider value={{
            gotRatio,
            ratio}}>
                {props.children}
        </PoseDataContext.Provider>
  )
}

export default PoseContext

My problem is that Video child use gotRatio function and update the value of ratio and shape component use ratio value to display it. But when gotRatio function update it re-render both Shape and Video component so Video start from 0sec again

Upvotes: 2

Views: 38

Answers (1)

ezio4df
ezio4df

Reputation: 4115

All the consumers will update its expected as of ReactJS Doc

All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. The propagation from Provider to its descendant consumers (including .contextType and useContext) is not subject to the shouldComponentUpdate method, so the consumer is updated even when an ancestor component skips an update.

Upvotes: 1

Related Questions