I have a custom hook with a useState holding a boolean value and function that allows me to update the state, I was expecting react to trigger a re render based on the new value but nothing happens
import React, { useState, useEffect } from 'react';
function useHook() {
const [value, setValue] = useState(false);
const onClick = (v) => {
setValue(v);
};
return {value, onClick};
}
const Switcher = () => {
const {value, onClick} = useHook();
return <button onClick={() => onClick(!value)}>test</button>;
};
export default function App() {
const {value} = useHook();
useEffect(() => {
console.log('effect', value);
}, [value]);
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>result {JSON.stringify(value)}</p>
<Switcher />
</div>
);
}
Hooks are ways to reuse behavior, not state. In other words, you’re creating 2 value states when you call useHook in App and Switcher, respectively. If you want to reuse state without just passing it via props, you’ll need to use something like redux or the Context API.
You have two separate calls to useHook which creates to separate states. What you want is one state that gets used in both components. Try passing value and onClick as props into Switcher from the parent component like so:
import React, { useState, useEffect } from 'react';
function useHook() {
const [value, setValue] = useState(false);
const onClick = (v) => {
setValue(v);
};
return {value, onClick};
}
const Switcher = ({onClick, value}) => {
return <button onClick={() => onClick(!value)}>test</button>;
};
export default function App() {
const {value, onClick} = useHook();
useEffect(() => {
console.log('effect', value);
}, [value]);
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>result {JSON.stringify(value)}</p>
<Switcher onClick={onClick} value={value}/>
</div>
);
}