The component props.
Optional
subscriptions: (string | number)[] = []Array of string object-paths in your component props you would like to update your component state for. By default, this is empty, and if left empty you will get only the initial props, and no updates. Each selected property is shallow compared with the previous version of that prop (not the current state). Only a change of prop will trigger a prop-based update and rerender.
Optional
updateAll: boolean = falseWhen true, an update to any subscribed object-path on your props will cause all the props to imprint on your component state.
An array containing [state, setState, forceRefresh]
import React from 'react';
import { useDerivedState } from '@atomic-reactor/reactium-sdk-core';
import op from 'object-path';
interface MyComponentProps {
path: {
to: {
value1: string;
value2: string;
}
}
}
const MyComponent: React.FC<MyComponentProps> = (props) => {
const [state, setState] = useDerivedState(props, ['path.to.value1', 'path.to.value2']);
const value1 = op.get(state, 'path.to.value1', 'Default value 1');
const value2 = op.get(state, 'path.to.value2', 'Default value 2');
// setState merges this object with previous state
const updateValue1 = () => setState({
path: {
to: {
value1: 'foo',
}
}
});
return (<div>
<div>Value 1: {value1}</div>
<div>Value 2: {value2}</div>
<button onClick={updateValue1}>Update Value 1</button>
</div>);
}
export default MyComponent;
import React from 'react';
import { useDerivedState } from '@atomic-reactor/reactium-sdk-core';
import op from 'object-path';
interface MyComponentProps {
user: {
name: string;
age: number;
}
}
const MyComponent: React.FC<MyComponentProps> = (props) => {
const [state, setState] = useDerivedState<MyComponentProps, MyComponentProps>(props, ['user.name', 'user.age']);
const userName = op.get(state, 'user.name', 'Default name');
const userAge = op.get(state, 'user.age', 'Default age');
// setState merges this object with previous state
const updateUserName = () => setState({
user: {
name: 'John Doe',
}
});
return (<div>
<div>Name: {userName}</div>
<div>Age: {userAge}</div>
<button onClick={updateUserName}>Update Name</button>
</div>);
}
export default MyComponent;
A React hook to derive state from your component props, and also allow either a prop change, or an internal state change either to take effect. This hook will allow you to create a state object from your component props, and subscribe (by array of object-paths) only to those prop changes you would like to see reflected in a rendering updates to your component state. This hook returns an array similar in nature to the return of React's built-in
useState()
hook ([state,setState]
), with some differences.