Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change react hook state from parent component

I have a hook component like this:

import React, { useState} from "react";

const MyComponent = props => {
  const [value, setValue] = useState(0);
  const cleanValue = () => {
    setValue(0);
  };

  return (<span><button onClick={()=>setValue(1)}/>{value}<span>)
}

I want to reset value from the parent component. How I can call clean value from parent component? the parent component is a stateful component.

like image 423
Hadi Ranjbar Avatar asked Apr 28 '19 10:04

Hadi Ranjbar


People also ask

How do I change the state of my child from parent in React?

To change child component's state from parent component with React, we can pass props. const Child = ({ open }) => { return <Drawer open={open} />; }; const ParentComponent = () => { const [isOpen, setIsOpen] = useState(false); const toggleChildMenu = () => { setIsOpen((prevValue) => !

How do you change the state of parent component from a child component in React hooks?

React hooks are introduced in React 16.8. If you are familiar with the class components then there is no difference to change the parent component state from child component. In both cases, you have to pass the callback function to the parent.

How do you pass data from parent to child in React hooks?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

How to change parent component state from child component in react?

React hooks are introduced in React 16.8. If you are familiar with the class components then there is no difference to change the parent component state from child component. In both cases, you have to pass the callback function to the parent. Let’s take a very simple example to understand it. We will take two components, Parent and Child.

How to change the name of a superhero component in react?

First, we will create a Superhero component with a name attribute in state. This component will render that name first. Now let’s create a function changeName () in the Superhero component. This function will change the name in state to the actual name of the superhero.

What is the difference between state and props in react?

We all know this, in React, state and props are two very important properties and are commonly used, easily explained: they are all used to save the state of the data. Props are used for communication between components, a way of passing data. Since React’s data flow is top to down, the props are passed from parent component to child component.

How to manage state on functional components in react?

There are many methods of managing state in React, including class-based state management and third-party libraries like Redux. In this tutorial, you’ll manage state on functional components using a method encouraged by the official React documentation: Hooks. Hooks are a broad set of tools that run custom functions when a component’s props change.


2 Answers

If the parent has to control the child state then probably the state must reside in the parent component itself. However you can still update child state from parent using ref and exposing a reset method in child. You can make use of useImperativeHandle hook to allow the child to only expose specific properties to the parent

const { useState, forwardRef, useRef, useImperativeHandle} = React;


const Parent = () => {
  const ref = useRef(null);
  return (
     <div>
      <MyComponent ref={ref} />
      <button onClick={() => {ref.current.cleanValue()}} type="button">Reset</button>
     </div>
  )
}

const MyComponent = forwardRef((props, ref) => {
  const [value, setValue] = useState(0);
  
   const cleanValue = () => {
    setValue(0);
  };

  useImperativeHandle(ref, () => {
     return {
      cleanValue: cleanValue
     }
  });

  return (<span><button type="button" onClick={()=>setValue(1)}>Increment</button>{value}</span>)
});
ReactDOM.render(<Parent />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/>
like image 69
Shubham Khatri Avatar answered Sep 17 '22 21:09

Shubham Khatri


From the React documentation about Fully uncontrolled component with a key:

In order to reset the value ..., we can use the special React attribute called key. When a key changes, React will create a new component instance rather than update the current one. Keys are usually used for dynamic lists but are also useful here.

In this case, we can use a simple counter to indicate the need for a new instance of MyComponent after pressing the Reset button:

const { useState } = React;

const Parent = () => {
  const [instanceKey, setInstanceKey] = useState(0)
  const handleReset = () => setInstanceKey(i => i + 1)
  return (
   <div>
    <MyComponent key={instanceKey} />
    <button onClick={handleReset} type="button">Reset</button>
   </div>
  )
}

const MyComponent = () => {
  const [value, setValue] = useState(0)
  return (
    <span>
      <button type="button" onClick={()=>setValue(v => v + 1)}>{value}</button>
    </span>
  )
};

ReactDOM.render(<Parent />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/>
like image 23
Aprillion Avatar answered Sep 19 '22 21:09

Aprillion