Controlled State Hook
Uncontrolled
const Counter = ({ value, onChange, defaultValue }) => {const [state, setState] = useControlledState(value, onChange, defaultValue);return (<button onClick={() => setState(state - 1)}>-</button><span>{state}</span><button onClick={() => setState(state + 1)}>+</button>)}export default () => (<Counter defaultValue={0} />)
0
Controlled
const Counter = ({ value, onChange, defaultValue }) => {const [state, setState] = useControlledState(value, onChange, defaultValue);return (<button onClick={() => setState(state - 1)}>-</button><span>{state}</span><button onClick={() => setState(state + 1)}>+</button>)}export default () => {const [value, setValue] = useState(0)return (<Counter value={0} onChange={setValue} />)}
0
Uncontrolled (subscribe on change)
const Counter = ({ value, onChange, defaultValue }) => {const [state, setState] = useControlledState(value, onChange, defaultValue);return (<button onClick={() => setState(state - 1)}>-</button><span>{state}</span><button onClick={() => setState(state + 1)}>+</button>)}export default () => (<Counter onChange={console.log} />)
0
Controlled (ignore changes)
const Counter = ({ value, onChange, defaultValue }) => {const [state, setState] = useControlledState(value, onChange, defaultValue);return (<button onClick={() => setState(state - 1)}>-</button><span>{state}</span><button onClick={() => setState(state + 1)}>+</button>)}export default () => {const [value, setValue] = useState(10)return (<Counter value={0} />)}
0