score:80

Accepted answer

You can create a method in your parent component, pass it to child component and call it from props every time child's state changes, keeping the state in child component.

    const EnhancedTable = ({ parentCallback }) => {
        const [count, setCount] = useState(0);
        
        return (
            <button onClick={() => {
                const newValue = count + 1;
                setCount(newValue);
                parentCallback(newValue);
            }}>
                 Click me {count}
            </button>
        )
    };

    class PageComponent extends React.Component { 
        callback = (count) => {
            // do something with value in parent component, like save to state
        }

        render() {
            return (
                <div className="App">
                    <EnhancedTable parentCallback={this.callback} />         
                    <h2>count 0</h2>
                    (count should be updated from child)
                </div>
            )
        }
    }

score:-7

I've had to deal with a similar issue, and found another approach, using an object to reference the states between different functions, and in the same file.

import React, { useState } from "react";

let myState = {};

const GrandParent = () => {
  const [name, setName] = useState("i'm Grand Parent");
  myState.name=name;
  myState.setName=setName;
  return (
    <>
      <div>{name}</div>
      <Parent />
    </>
  );
};
export default GrandParent;

const Parent = () => {
  return (
    <>
      <button onClick={() => myState.setName("i'm from Parent")}>
        from Parent
      </button>
      <Child />
    </>
  );
};

const Child = () => {
  return (
    <>
      <button onClick={() => myState.setName("i'm from Child")}>
        from Child
      </button>
    </>
  );
};

score:0

I had to do this in type script. The object-oriented aspect would need the dev to add this callback method as a field in the interface after inheriting from parent and the type of this prop would be Function. I found this cool!

score:0

Here's an another example of how we can pass state directly to the parent.

I modified a component example from react-select library which is a CreatableSelect component. The component was originally developed as class based component, I turned it into a functional component and changed state manipulation algorithm.

import React, {KeyboardEventHandler} from 'react';
import CreatableSelect from 'react-select/creatable';
import { ActionMeta, OnChangeValue } from 'react-select';

const MultiSelectTextInput = (props) => {
    const components = {
        DropdownIndicator: null,
    };

    interface Option {
        readonly label: string;
        readonly value: string;
    }

    const createOption = (label: string) => ({
        label,
        value: label,
    });

    const handleChange = (value: OnChangeValue<Option, true>, actionMeta: ActionMeta<Option>) => {
        console.group('Value Changed');
        console.log(value);
        console.log(`action: ${actionMeta.action}`);
        console.groupEnd();
        props.setValue(value);
    };

    const handleInputChange = (inputValue: string) => {
        props.setInputValue(inputValue);
    };

    const handleKeyDown: KeyboardEventHandler<HTMLDivElement> = (event) => {
        if (!props.inputValue) return;

        switch (event.key) {
            case 'Enter':
            case 'Tab':
                console.group('Value Added');
                console.log(props.value);
                console.groupEnd();
                props.setInputValue('');
                props.setValue([...props.value, createOption(props.inputValue)])
                event.preventDefault();
        }
    };

    return (
        <CreatableSelect
            id={props.id}
            instanceId={props.id}
            className="w-100"
            components={components}
            inputValue={props.inputValue}
            isClearable
            isMulti
            menuIsOpen={false}
            onChange={handleChange}
            onInputChange={handleInputChange}
            onKeyDown={handleKeyDown}
            placeholder="Type something and press enter..."
            value={props.value}
        />
    );
};

export default MultiSelectTextInput;

I call it from the pages of my next js project like this

import MultiSelectTextInput from "../components/Form/MultiSelect/MultiSelectTextInput";

const NcciLite = () => {
    const [value, setValue] = useState<any>([]);
    const [inputValue, setInputValue] = useState<any>('');

    return (
        <React.Fragment>
            ....
            <div className="d-inline-flex col-md-9">
                <MultiSelectTextInput
                    id="codes"
                    value={value}
                    setValue={setValue}
                    inputValue={inputValue}
                    setInputValue={setInputValue}
                />
            </div>
            ...
        </React.Fragment>
    );
};

As seen, the component modifies the page's (parent page's) state in which it is called.

score:0

IF we Have Parent Class Component and Child function component this is how we going to access child component useStates hooks value :--

class parent extends Component() {
 
  constructor(props){
    super(props)
    this.ChildComponentRef = React.createRef()   
  }
  
  render(){
    console.log(' check child stateValue: ', 
    this.ChildComponentRef.current.info);
    return (<> <ChildComponent ref={this.ChildComponentRef} /> </>)
 }
}

Child Component we would create using

React.forwardRef((props, ref) => (<></>))

. and

useImperativeHandle(ref, createHandle, [deps])

to customizes the instance value that is exposed to parent components

const childComponent = React.forwardRef((props, ref) => {
   const [info, setInfo] = useState("")

   useEffect(() => {
      axios.get("someUrl").then((data)=>setInfo(data))
   })

  useImperativeHandle(ref, () => {
      return {
          info: info
      }
  })
  return (<> <h2> Child Component <h2> </>)
 })

score:60

To make things super simple you can actually share state setters to children and now they have the access to set the state of its parent.

example: Assume there are 4 components as below,

function App() {
  return (
    <div className="App">
      <GrandParent />
    </div>
  );
}

const GrandParent = () => {
  const [name, setName] = useState("i'm Grand Parent");
  return (
    <>
      <div>{name}</div>
      <Parent setName={setName} />
    </>
  );
};

const Parent = params => {
  return (
    <>
      <button onClick={() => params.setName("i'm from Parent")}>
        from Parent
      </button>
      <Child setName={params.setName} />
    </>
  );
};

const Child = params => {
  return (
    <>
      <button onClick={() => params.setName("i'm from Child")}>
        from Child
      </button>
    </>
  );
};

so grandparent component has the actual state and by sharing the setter method (setName) to parent and child, they get the access to change the state of the grandparent.

you can find the working code in below sandbox, https://codesandbox.io/embed/async-fire-kl197

score:115

A common technique for these situations is to lift the state up to the first common ancestor of all the components that needs to use the state (i.e. the PageComponent in this case) and pass down the state and state-altering functions to the child components as props.

Example

const { useState } = React;

function PageComponent() {
  const [count, setCount] = useState(0);
  const increment = () => {
    setCount(count + 1)
  }

  return (
    <div className="App">
      <ChildComponent onClick={increment} count={count} />         
      <h2>count {count}</h2>
      (count should be updated from child)
    </div>
  );
}

const ChildComponent = ({ onClick, count }) => {
  return (
    <button onClick={onClick}>
       Click me {count}
    </button>
  )
};

ReactDOM.render(<PageComponent />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>


Related Query

More Query from same tag