2 ms·
You're dramatically overexaggerating the complications of global state handling in Redux. For a simple app, you could just use the useState hook, and pass the s
by crooked-v 8y ago
You're dramatically overexaggerating the complications of global state handling in Redux. For a simple app, you could just use the useState hook, and pass the state-setting callback down into children components:
import React, { useState } from 'react';
export const SetterButton = ({ children, ...rest }) => (
<button type="button" {...rest}>{children}</button>
)
export const BoxComponent = ({ label }) => {
const [value, setValue] = useState(0);
return (
<div style={border: '1px solid black'}>
{label}: {value}
<SetterButton onClick={() => setValue(value + 1)}>+1</SetterButton>
</div>
);
};
Or for a bigger app with many nested components, you can use context:
import React, { useState } from 'react';
export const ValueContext = React.createContext();
export const SubComponent = () => (
<div>
<p>
Here's a value:
<ValueContext.Consumer>
{({ value }) => value}
</ValueContext.Consumer>
</p>
<p>
Here's a button:
<ValueContext.Consumer>
{({ setValue, value }) => <button type="button" onClick={() => setValue(value + 1)}>+1</button>}
</ValueContext.Consumer>
</p>
</div>
)
export const App = () => {
const [value, setValue] = useState();
return (
<ValueContext.Provider value={{ value, setValue }}>
Some other stuff goes here.
<SubComponent></SubComponent>
</ValueContext.Provider>
);
}
None of this takes a ton of thought. Just make a file for contexts exports and a root level component with any Providers.