react parent send "event" to child - reactjs

I am running some tests with react to find out a way for a parent to send an "event" to a child component. In the test application, the parent (CounterController) has a button. When the button is clicked, the parent shall send a reset "event" to the child (Counter) to reset the current count. Like below.
I am new to react, and can not find a way to dispatch/receive events or messages between components. I had a thought to mark the "reset" request as a "state" in the parent, then pass it to the child through props. Then the child clear the "reset" state, through a callback function, to avoid repeating "reset" requests. However, I got the code run into an infinite loop. Here are my codes.
The parent component - CounterController
The child component - Counter
the error logs
I do not feel that I am using react the right way, by asking the child to do something from the parent. Anyway, any idea about how to implement this app in react? How should the data flow be built correctly? Thanks!

You can move up the counter state on the parent ‘CounterController’
and then you pass the counter and setCounter as props to ‘Counter’
You don’t need ‘reset’ state

I am posting my thoughts about using react (as a beginner), and my solution to the app.
treat the react components as the "view" of the application, and maintain the data and controls in the hooks.
create a custom hook to wrap up all data and controls.
create an instance of the custom hook in the top component - display the data in HTML elements and bound controls to buttons to build the app UI
Here are my codes for this simple UI
UI
useCounter hook
counterController component
counter component

Move "count" state from child component (Counter) to parent
component (CounterController).
Pass count state as prop to child component.
Pass increment and decrement methods from parent to child component through props.
Note: Remove reset state, it's not required anymore.
Sandbox link : https://codesandbox.io/s/infallible-platform-vo4qtv?file=/src/CountController.js

Related

React parent to child props passing without rerender

I have a button on my parent component and a third-party form in a child component. When the user clicks the button, the save function in the child component should run. This is my plan.
Method 1 I tried:
1.Created a variable on parent called save.
2. When button is clicked, save becomes true
3. Save is passed down to the child as props
4. Child contains a useEffect() which listens to changes in props.save
5. If props.save is true, save function of child component runs
Method 2 I tried:
Instead of passing props, I created a react-redux store.
The store contains save variable which is false by default
When button is clicked, save in redux becomes true
I use useSelector() hook to listen to the save variable change, inside the child component
UseEffect is used to run the save() function when the value change is detected
What happens with both methods is that I am losing the data in my child component because the variable change in the parent causes a page refresh. Therefore I want to pass the data down to the child, without causing rerenders. What are the options I have?
Thanks in advance
Thanks to #Shyam, I could finally solve this issue!
My assumption that useState and props cause render was correct. And as #Shyam suggested, there is no direct way to avoid it.
I am using react-editor-js in my project and that's what caused the issue
<EditorJs
instanceRef={()=>{//code to save the reference as state variable}}
enableReInitialize
data={{}}
tools={EDITOR_JS_TOOLS}
/>
The reason for state loss was that my instanceRef was being reassigned every time the component renders.
This reassignment can be prevented by wrapping the method to save the reference as a state variable with useCallback()

React - How to connect / disconnect children components to data from parent based on click?

Parent component provides data to child component (that displays it) (have multiple children). The child component has 2 buttons connect and disconnect. When connected to should receive and show the data, when disconnected clicked, it should disconnect from data.
How I would do it: child calls method in parent for connect/disconnect,then i would have a flag in parent state and based on that either render child with or without data, then inside child i render props or null if no props provided.
That would mean if I have 10 child components, I would need 10 flags which doesnt seem good, so I 2nd idea:
having the flag insight the child and method for triggering connect/disconnect, render based on if props were provided
My question is, is there a good practice react way of connecting children to parents data flow/stopping data flow without always passing data to children and just rendering/not rendering it based on if child 'wans' to be conencted or not?
Thanks!
Did you try using Redux or Context API?
The two are very similar and it should get what you want.
They basically use 1 store(think of them multiple states are connected to 1 store) and you get data from child components.
After getting your data you can check if user is logged in or not and put your buttons according to this data.
If I was not clear enough feel free to ask any question.
Also official docs for Redux and Context API are:
https://redux.js.org/introduction/getting-started
https://tr.reactjs.org/docs/context.html

How can I call child component setState from parent component

I have 2 stateful class-based components nested within my main app, a parent class-based component. From child component 1, I've successfully called a parent callback method. From within that parent callback I want to call a method of child component 2, so I can setState of #2 without re-rendering the parent component. I've seen that many devs make the children stateless or even just omit them. However, React encourages devs to "componenatize" ... pointers plz!
if that's the case then you shoud consider lifting the state up to the parent: https://reactjs.org/docs/lifting-state-up.html
your child component should only then call parent methods to update the state, that way, you will have a unidirectional flow of data as what a react app should be. Basically, it encourages you to have a single source of truth and ensure synchronisation of data across your app. Besides it removes unnecessary logic like what you are doing right now:
What does the "single source of truth" mean?
Storing the data in the parent's state and then allowing both children to update it via setStates wouldn't violate the concept of "componentizing" as long as the two children have narrowly declared inputs. If one child needs to update data inside another child, you can jump up a context level and store it in the parent- then an update of the data from either child will trigger a render of both children ensuring the display stays synchronized with the data while keeping the data in a single place (with the parent instead of split between the children).
Bingo, yes I can use a "React ref" to call an instance method of a child component. A ref is an attribute on a component instance. So, right now my child component uses its componentDidUpdate to call a callback in my parent, and the parent callback then uses refs to call an "update" method of specific child components. These update methods setState on child component and voila.
So a colleague explained that calling setState in my main app actually will call setState on all children components (related by JSX expressions). Even though I liked the idea of nesting my event handlers within their relevant child components, it seems that the best practice pattern is to have all handlers in the main app, setState in the main app, then let React do its thing

When a component can edit properties in react?

I was going through a code and found that
this.props.formVisibility = false
As one cannot update the properties in react's component, the code shouldnt have work but the execution went without any errors.
Now I am wondering, On what conditions one is able to edit props in the component?
Suppose you have parent - child relationship. where parent's state pass as props to child component then whenever you want to update props you need to update parents state not props in child component. once state get updated this will update to props as well in child component hope so it clear the point
refer : https://gist.github.com/sebkouba/a5ac75153ef8d8827b98

State of child components in React

Should child components never have a state in React? I understand that state should be maintained by the "wrapper container" or parent container and it should have unidirectional flow. I have started with React and have a header container with upto 10 child components.
Let's say one of the child component is a Form with a submit button that can be enabled or disabled.
Should this child component not be able to have a constructor with state initialized for the button and be able to directly manipulate it or is it important that I maintain states as minute as this in the wrapper container "only"?
You should let the parent container manage the state of forms. I usually attach an onChange listener to each input and then when the submit button is clicked I call a function in the parent component to submit the value contained in the state for my form inputs. The form should only render inputs and do nothing else, basically a dumb component.
The purpose of React is providing a component system to front-end. It does not specify/enforce how state flow. People generally prefer state-less components because it is easier to share and distribute. However, front-end component can never be fully state-less + declarative.
In my opinion, you should feel free to use this.state to manage local state when you feel appropriate.

Resources