What is the recommended pattern for doing a setState on a parent from a child component.
var Todos = React.createClass({
getInitialState: function() {
For those who are maintaining state with the React Hook useState, I adapted the above suggestions to make a demo slider App below. In the demo app, the child slider component maintains the parent's state.
The demo also uses useEffect hook. (and less importantly, useRef hook)
import React, { useState, useEffect, useCallback, useRef } from "react";
//the parent react component
function Parent() {
// the parentState will be set by its child slider component
const [parentState, setParentState] = useState(0);
// make wrapper function to give child
const wrapperSetParentState = useCallback(val => {
setParentState(val);
}, [setParentState]);
return (
Parent State: {parentState}
);
};
//the child react component
function Child({parentStateSetter}) {
const childRef = useRef();
const [childState, setChildState] = useState(0);
useEffect(() => {
parentStateSetter(childState);
}, [parentStateSetter, childState]);
const onSliderChangeHandler = e => {
//pass slider's event value to child's state
setChildState(e.target.value);
};
return (
);
};
export default Parent;