Issue
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.
Solution
Appreciate the change you want to point out and value you want to add but there might be some points that you're missing what React conceptually trying to provide with seperation between props and state.
The props within components coming with React are specifically conceptually designed to be immutable as per the documentation here.
So what you're trying to do is conceptually not ok for that purpose and violating what React tries to accomplish.
Infact you may mention about creating another library/framework which successfully getting it done while introducing props are the new state
concept but in this specific case, there's no possible way to succeed on it in a React way.
Answered By - Erhan Yaşar
Answer Checked By - - Dawn Plyler (ReactFix Volunteer)