Rafael Zeferino Rossi
Rafael Zeferino Rossi

Reputation: 51

How to update parent's variable from a child component

I'm currently in a situation where I need to update a value outside of the current component that i'm using. I tried passing the set function from useState, but react returns an error: "Cannot update a component (Parent) while rendering a different component (Child)."

What I have so far:

Parent Component

import React, { useState } from 'react';
import { Child } from './child';

export const Parent = () => {
  const [x, setX] = useState<number>(0);


  return(
    <>
      <Child function={setX} />
   </>
  )
}
 

Child Component

import React from 'react';

interface ChildProps {
  function: Function
}

export const Child = (props: ChildProps) => {

  props.function(5);

  return(
    <>
    </>
  )
}

Since probably I can't do that with useState, I would like to know what I can do, to perform this task.

Upvotes: 1

Views: 92

Answers (1)

Francisco
Francisco

Reputation: 1773

Of course you can call a function passed via props. Try to call the function when the component is rendered using the useEffect hook.

!!ALSO!! - don't use the keyword function for the prop. Use another word, fn setX....

Child component:

import React from 'react';

interface ChildProps {
  fn: Function
}

export const Child = (props: ChildProps) => {

  useEffect(() => {
    props.fn(5);    
  }, []);


  return(
    <>
    </>
  )
}

Upvotes: 2

Related Questions