I want to do something like this:
const GreetingWithCounter = (props) => {
const { name, count } = props;
return (
<div>
<div>Hello {name}</div>
<button onClick={() => render({ ...props, count: count + 1 })}>
{count}
</button>
</div>
);
}
<GreetingWithCounter name="Alice" count={0} />
Ie. I want to re-render a component with new values for its props
. Is there a way to do that? Looking through these three questions, I'm seeing ways to re-render a component but not with new values for props (1, 2, 3).
Context
I'm thinking about a way to simplify React. I really like the mental model of React being the view layer in MVC, where UI = F(state). But things can get confusing when "state" can come from so many different places: props
, useState
, useReducer
, "raw" useContext
, Redux (which uses useContext
I think), whatever else.
What if everything was just based off of props?
- For local state you'd do what I did in that example above. You'd initialize the local state of
count
when doing<GreetingWithCounter name="Alice" count={0} />
and then update it by re-rendering. This means less DRYness because you'd have to repeat thecount={0}
code instead of only having it once inside ofGreetingWithCounter
. - You'd have to do prop drilling instead of
useContext
stuff. - This approach would probably make React slower.
- Still, I hypothesize 1) that the mental model of having everything coming from props is simpler and 2) that pro outweighs the cons in a non-trivial amount of apps.