Ancross
Ancross

Reputation: 25

Is there a way to refresh a childs state from a parent component (Both are function components)

function clearChildState(){
  //Stuff to clear child state from parent components
}

I want an input from the user (Who sees the parent component) to click a button to clear child components states. How would one go about this?

Upvotes: 0

Views: 1105

Answers (2)

Beyro
Beyro

Reputation: 119

If you must use function components, you could use refs and effects to do it like this:

const ChildComponent = (props) => {
  
  // Store your initial state
  const initialState = {
    name: 'Default Name',
    title: 'Default Title'
  }
  
  const [{name, title} , setState] = React.useState(initialState)
  const setNewState = () => {
    setState({ name: 'New Name', title: 'New Title' })
  }
  
  // Use a ref to store the previous prop value
  const prevClearChildStateCount = React.useRef(0)
  
  // Use effects to run a check whenever the prop is updated
  React.useEffect(() => {
    if (props.clearChildStateCount > prevClearChildStateCount.current) {
      setState(initialState)
    }
    prevClearChildStateCount.current = props.clearChildStateCount
  }, [props.clearChildStateCount])
  
  return (
    <div>
      <p>Name: {name}</p>
      <p>Title: {title}</p>
      <button onClick={setNewState}>Set new state</button>
    </div>
  )
}

const ParentComponent = () => {
  const [clearChildStateCount, updateClearChildState] = React.useState(0)
  const clearChildState = () => {
    updateClearChildState(clearChildStateCount + 1)
  }
  return (
    <div>
      <ChildComponent clearChildStateCount={clearChildStateCount} />
      <button onClick={clearChildState}>Clear Child State</button>
    </div>
  )
}

ReactDOM.render(<ParentComponent />, document.getElementById('container'))

Link to Fiddle

Upvotes: 0

Nice Books
Nice Books

Reputation: 1861

You can pass the items as prop (parent->child).

<Child items={items} />

The child continues to have an items state, which is initialized from the items prop.
When the parent passes an empty array to the child, the child's items state would be reset to [].

This can be achieved using getDerivedStateFromProps in class based child component.

class Child extends React.Component {

    constructor(props) {
        super(props);
        this.state = {items: []};
    }

    static getDerivedStateFromProps(props,state) {
        return {items: props.items};
    }   

    // render
}

Upvotes: 1

Related Questions