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