If you are referring to component state, then hooks will not help you share it between components. Component state is local to the component. If your state lives in context, then useContext hook would be helpful.
Fundamentally, I think you misunderstood the line "sharing stateful logic between components". Stateful logic is different from state. Stateful logic is stuff that you do that modifies state. For e.g., a component subscribing to a store in componentDidMount() and unsubscribing in componentWillUnmount(). This subscribing/unsubscribing behavior can be implemented in a hook and components which need this behavior can just use the hook.
If you want to share state between components, there are various ways to do so, each with its own merits:
1. Lift State Up
Lift state up to a common ancestor component of the two components.
function Ancestor() {
const [count, setCount] = useState(999);
return <>
<DescendantA count={count} onCountChange={setCount} />
<DescendantB count={count} onCountChange={setCount} />
</>;
}
This state sharing approach is not fundamentally different from the traditional way of using state, hooks just give us a different way to declare component state.
2. Context
If the descendants are too deep down in the component hierarchy and you don't want to pass the state down too many layers, you could use the Context API.
There's a useContext hook which you can leverage on within the child components.
3. External State Management Solution
State management libraries like Redux or Mobx or Zustand. Your state will then live in a store outside of React and components can connect/subscribe to the store to receive updates.
Answer from Yangshun Tay on Stack OverflowIf you are referring to component state, then hooks will not help you share it between components. Component state is local to the component. If your state lives in context, then useContext hook would be helpful.
Fundamentally, I think you misunderstood the line "sharing stateful logic between components". Stateful logic is different from state. Stateful logic is stuff that you do that modifies state. For e.g., a component subscribing to a store in componentDidMount() and unsubscribing in componentWillUnmount(). This subscribing/unsubscribing behavior can be implemented in a hook and components which need this behavior can just use the hook.
If you want to share state between components, there are various ways to do so, each with its own merits:
1. Lift State Up
Lift state up to a common ancestor component of the two components.
function Ancestor() {
const [count, setCount] = useState(999);
return <>
<DescendantA count={count} onCountChange={setCount} />
<DescendantB count={count} onCountChange={setCount} />
</>;
}
This state sharing approach is not fundamentally different from the traditional way of using state, hooks just give us a different way to declare component state.
2. Context
If the descendants are too deep down in the component hierarchy and you don't want to pass the state down too many layers, you could use the Context API.
There's a useContext hook which you can leverage on within the child components.
3. External State Management Solution
State management libraries like Redux or Mobx or Zustand. Your state will then live in a store outside of React and components can connect/subscribe to the store to receive updates.
It is possible without any external state management library. Just use a simple observable implementation:
function makeObservable(target) {
let listeners = []; // initial listeners can be passed an an argument aswell
let value = target;
function get() {
return value;
}
function set(newValue) {
if (value === newValue) return;
value = newValue;
listeners.forEach((l) => l(value));
}
function subscribe(listenerFunc) {
listeners.push(listenerFunc);
return () => unsubscribe(listenerFunc); // will be used inside React.useEffect
}
function unsubscribe(listenerFunc) {
listeners = listeners.filter((l) => l !== listenerFunc);
}
return {
get,
set,
subscribe,
};
}
And then create a store and hook it to react by using subscribe in useEffect:
const userStore = makeObservable({ name: "user", count: 0 });
const useUser = () => {
const [user, setUser] = React.useState(userStore.get());
React.useEffect(() => {
return userStore.subscribe(setUser);
}, []);
const actions = React.useMemo(() => {
return {
setName: (name) => userStore.set({ ...user, name }),
incrementCount: () => userStore.set({ ...user, count: user.count + 1 }),
decrementCount: () => userStore.set({ ...user, count: user.count - 1 }),
}
}, [user])
return {
state: user,
actions
}
}
And that should work. No need for React.Context or lifting state up
How to access one component's state from another component
reactjs - React - how to pass state to another component - Stack Overflow
How do I call setState from another Component in ReactJs - Stack Overflow
How does one useState across components OR modules?
I'm new to React/Typescript with a Java/Python background. Maybe I am misunderstanding how to do this (or perhaps its some sort of anti-pattern..) but is it really hard to share state variables between components? What if I have an inputbutton component that acts as a setter for a state variable and another component that relies on the output of setter?
It seems quite complicated too create a parent component and propagate the props through that...
Even if you try doing this way, it is not correct method to access the state. Better to have a parent component whose children are a and b. The ParentComponent will maintain the state and pass it as props to the children.
For instance,
var ParentComponent = React.createClass({
getInitialState : function() {
return {
first: 1,
}
}
changeFirst: function(newValue) {
this.setState({
first: newValue,
});
}
render: function() {
return (
<a first={this.state.first} changeFirst={this.changeFirst.bind(this)} />
<b first={this.state.first} changeFirst={this.changeFirst.bind(this)} />
)
}
}
Now in your child compoenents a and b, access first variable using this.props.first. When you wish to change the value of first call this.props.changeFirst() function of the ParentComponent. This will change the value and will be thus reflected in both the children a and b.
I am writing component a here, b will be similar:
var a = React.createClass({
render: function() {
var first = this.props.first; // access first anywhere using this.props.first in child
// render JSX
}
}
If two components need access to the same state they should have a common ancestor where the state is kept.
So component A is the parent of B and C. Component A has the state, and passes it down as props to B and C. If you want to change the state from B you pass down a callback function as a prop.
If you work with functional components you can use hooks like useState. Don't forget to "save" (memoize) the reference of your handler with useCallback, it helps React avoid useless rerenders.
Functional component solution
// myContainer.js
import React, { useState } from 'react'
import MyChild from 'some/path/myChild'
function MyContainer() {
const [name, setName] = useState('foo')
return (
<MyChild name={name} onNameChange={setName} />
)
}
export default MyContainer
// myChild.js
import React, { useCallback } from 'react'
function MyChild({ name, onNameChange }) {
const handleInputChange = useCallback(event => {
onNameChange(event.target.value)
}, [onNameChange])
return (
<div>
<input type="text" onChange={handleInputChange} value={name} />
<div>The name is: {name}</div>
</div>
)
}
export default MyChild
In a class you can use handler (method) that contains some logic or function call(s). It help to keep your code maintainable.
Class component solution
// myContainer.js
import React, { Component } from 'react'
import MyChild from 'some/path/myChild'
class MyContainer extends Component {
state = {
name: 'foo'
}
handleNameChange = name => {
this.setState({ name })
}
render() {
return (
<MyChild name={this.state.name} onNameChange={this.handleNameChange} />
)
}
}
export default MyContainer
// myChild.js
import React, { Component } from 'react'
class MyChild extends Component {
handleInputChange = event => {
this.props.onNameChange(event.target.value)
}
render() {
return (
<div>
<input type="text" onChange={this.handleInputChange} value={this.props.name} />
<div>The name is: {this.props.name}</div>
</div>
)
}
}
export default MyChild
You can't directly call setState on a parent component from a child component because the updating of a component state is restricted to the current component.
To handle this, simply pass a function from the parent to the child that contains setState. So when you want to update the parent's state, just call that passed function.
A minimal example:
// Parent.jsx
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
constructor(props) {
super(props);
this.setChanged = this.setChanged.bind(this);
this.state = {
changed: false
}
}
// Function to set the parent's state
setChanged() {
this.setState({ changed: true });
}
render() {
return <Child setChanged={this.setChanged} />
}
}
// Child.js
import React from 'react';
function Child(props) {
return (
// When clicked, parent's setChanged function is called
<div onClick={() => props.setChanged()} />
)
}
If I want to set setState() in a separate file using a module import in my primary file, where my const [state, setState] = useState() resides, how do I go about it?
What do I do if I have state in component A and I have another component B in which I have a input field that is supposed to update the state in component A.
In order not going to post my entire code which is a lot, I came up with this simpler situation that still applies to me.
const parentComponent = () => {
return (
<div>
<childOne />
<childTwo />
</div>
);
}
const childOne = () => {
const [money, setMoney] = useState(5);
return (
<div>
Money Raised: {money}
</div>
);
}
const childTwo = () => {
return (
<div>
<grandChildComponent />//This component is supposed to update money
</div
);
}
Is it possible to update money from grandChildComponent?
The reason why I want to do this is because I have a input field in grandChildComponent that is supposed to get a value and then I want to update the money state with the value that I got from grandChildComponent
I have no idea if I explained this correctly, I'm sorry..